Requests, bind to an ip

前端 未结 1 955
自闭症患者
自闭症患者 2020-11-27 05:56

I have a script that makes some requests with urllib2.

I use the trick suggested elsewhere on Stack Overflow to bind another ip to the application, wher

相关标签:
1条回答
  • 2020-11-27 06:44

    Looking into the requests module, it looks like it uses httplib to send the http requests. httplib uses socket.create_connection() to connect to the www host.

    Knowing that and following the monkey patching method in the link you provided:

    import socket
    
    real_create_conn = socket.create_connection
    
    def set_src_addr(*args):
        address, timeout = args[0], args[1]
        source_address = ('IP_ADDR_TO_BIND_TO', 0)
        return real_create_conn(address, timeout, source_address)
    
    socket.create_connection = set_src_addr
    
    import requests
    r = requests.get('http://www.google.com')
    

    It looks like httplib passes all the arguments (to create_connection()) as args (vs keywords) as trying to extend the kwargs dict inside set_src_addr was failing. I believe the above is what you want, but I don't have a dual homed machine to test on.

    0 讨论(0)
提交回复
热议问题