Force requests to use IPv4 / IPv6

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

    This is a hack, but you can monkey-patch getaddrinfo to filter to only IPv4 addresses:

    # Monkey patch to force IPv4, since FB seems to hang on IPv6
    import socket
    old_getaddrinfo = socket.getaddrinfo
    def new_getaddrinfo(*args, **kwargs):
        responses = old_getaddrinfo(*args, **kwargs)
        return [response
                for response in responses
                if response[0] == socket.AF_INET]
    socket.getaddrinfo = new_getaddrinfo
    

提交回复
热议问题