X
X
xiii062021-11-15 17:58:00
Python
xiii06, 2021-11-15 17:58:00

How to use Python requests with additional server IPs?

There is a VPS server on Ubuntu 18.04. I bought and tied additional IP addresses from the provider.
How do I make requests to an external resource using a specific IP?
Using requests.post, Python3+ language

Example of how it should work:
requests.post(' https://google.com ', IP1)
requests.post(' https://google.com ', IP2)

Where IP1 and 2 are these are additional external IP addresses specified in Ubuntu network settings

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2021-12-06
@Survtur

From here

import requests


def session_for_src_addr(addr: str) -> requests.Session:
    """
    Create `Session` which will bind to the specified local address
    rather than auto-selecting it.
    """
    session = requests.Session()
    for prefix in ('http://', 'https://'):
        session.get_adapter(prefix).init_poolmanager(
            # those are default values from HTTPAdapter's constructor
            connections=requests.adapters.DEFAULT_POOLSIZE,
            maxsize=requests.adapters.DEFAULT_POOLSIZE,
            # This should be a tuple of (address, port). Port 0 means auto-selection.
            source_address=(addr, 0),
        )

    return session


# usage example:
s = session_for_src_addr('192.168.1.12')
s.get('https://httpbin.org/ip')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question