You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
How to send http request through specific network interface? #2631
I have two network interfaces and both with internet access. Let's say my interfaces are eth0 and ETH999. I need specific requests to go through ETH999 interface and eth0 is the default interface in my server.
I can do this with these codes when I use requests.
import socket
import requests
from requests import adapters
from urllib3.poolmanager import PoolManager
class InterfaceAdapter(adapters.HTTPAdapter):
def __init__(self, **kwargs):
self.iface = kwargs.pop('iface', None)
super(InterfaceAdapter, self).__init__(**kwargs)
def _socket_options(self):
if self.iface is None:
return []
else:
return [(socket.SOL_SOCKET, socket.SO_BINDTODEVICE, self.iface)]
def init_poolmanager(self, connections, maxsize, block=False):
self.poolmanager = PoolManager(
num_pools=connections,
maxsize=maxsize,
block=block,
socket_options=self._socket_options()
)
session = requests.Session()
for prefix in ('http://', 'https://'):
# set ETH999 interface here
session.mount(prefix, InterfaceAdapter(iface=ETH999'))
print(session.get("https://ifconfig.me/").text
Activity