Skip to content

How to send http request through specific network interface? #2631

Description

@ChrisYP

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

so how to do the same on Httpx? thanks.

Activity

  1. locked and limited conversation to collaborators on Mar 27, 2023
  2. converted this issue into a discussion #2635 on Mar 27, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions