Force requests to use IPv4 / IPv6

后端 未结 6 899
走了就别回头了
走了就别回头了 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:39

    After reading the previous answer, I had to modify the code to force IPv4 instead of IPv6. Notice that I used socket.AF_INET instead of socket.AF_INET6, and self.sock.connect() has 2-item tuple argument.

    I also needed to override the HTTPSConnection which is much different than HTTPConnection since requests wraps the httplib.HTTPSConnection to verify the certificate if the ssl module is available.

    import socket
    import ssl
    try:
        from http.client import HTTPConnection
    except ImportError:
        from httplib import HTTPConnection
    from requests.packages.urllib3.connection import VerifiedHTTPSConnection
    
    # HTTP
    class MyHTTPConnection(HTTPConnection):
        def connect(self):
            self.sock = socket.socket(socket.AF_INET)
            self.sock.connect((self.host, self.port))
            if self._tunnel_host:
                self._tunnel()
    
    requests.packages.urllib3.connectionpool.HTTPConnection = MyHTTPConnection
    requests.packages.urllib3.connectionpool.HTTPConnectionPool.ConnectionCls = MyHTTPConnection
    
    # HTTPS
    class MyHTTPSConnection(VerifiedHTTPSConnection):
        def connect(self):
            self.sock = socket.socket(socket.AF_INET)
            self.sock.connect((self.host, self.port))
            if self._tunnel_host:
                self._tunnel()
            self.sock = ssl.wrap_socket(self.sock, self.key_file, self.cert_file)
    
    requests.packages.urllib3.connectionpool.HTTPSConnection = MyHTTPSConnection
    requests.packages.urllib3.connectionpool.VerifiedHTTPSConnection = MyHTTPSConnection
    requests.packages.urllib3.connectionpool.HTTPSConnectionPool.ConnectionCls = MyHTTPSConnection
    

提交回复
热议问题