Force requests to use IPv4 / IPv6

后端 未结 6 900
走了就别回头了
走了就别回头了 2020-12-01 14:58

How to force the requests library to use a specific internet protocol version for a get request? Or can this be achieved better with another method in Python? I

6条回答
  •  無奈伤痛
    2020-12-01 15:12

    This is totally untested and will probably require some tweaks, but combining answers from Using Python “requests” with existing socket connection and how to force python httplib library to use only A requests, it looks like you should be able to create an IPv6 only socket and then have requests use that for its connection pool with something like:

    try:
        from http.client import HTTPConnection
    except ImportError:
        from httplib import HTTPConnection
    
    class MyHTTPConnection(HTTPConnection):
        def connect(self):
            print("This actually called called")
            self.sock = socket.socket(socket.AF_INET6)
            self.sock.connect((self.host, self.port,0,0))
            if self._tunnel_host:
                self._tunnel()
    
    requests.packages.urllib3.connectionpool.HTTPConnection = MyHTTPConnection
    

提交回复
热议问题