Send http request through specific network interface

后端 未结 3 1466
春和景丽
春和景丽 2020-12-07 01:46

I have two network interfaces (wifi and ethernet) both with internet access. Let\'s say my interfaces are eth (ethernet) and wlp2 (wifi). I need sp

3条回答
  •  心在旅途
    2020-12-07 02:02

    Here is the solution for Requests library without monkey-patching anything.

    This function will create a Session bound to the given IP address. It is up to you to determine IP address of the desired network interface.

    Tested to work with requests==2.23.0.

    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')
    

    Be warned though that this approach is identical to curl's --interface option, and won't help in some cases. Depending on your routing configuration, it might happen that even though you bind to the specific IP address, request will go through some other interface. So if this answer does not work for you then first check if curl http://httpbin.org/ip --interface myinterface will work as expected.

提交回复
热议问题