Anorov/PySocks

Fixing `socketpair()` hang on Windows

hanayashiki opened this issue · 0 comments

On windows if you run the following:

import socks
import socket
import requests

version = "SOCKS5"
addr = "localhost"
port = 1080

socks.set_default_proxy(socks.PROXY_TYPES[version], addr, port)
socket.socket = socks.socksocket

print("Start...")
socket.socketpair()
print("End")

You will get

Start...

And python hangs and does not react to ctrl+c.

After looking into the code, I find that socketpair uses 127.0.0.1 addresses, which calls socks.socksocket to connect to 127.0.0.1, which is not what we desire. A choice to resolve this might be only running socket.socket = socks.socksocket after any socketpair is made, or the following monkeypatch to avoid connection to a local address by socks:

  def wrap_connect(func):
    def _connect(self, address: Union[tuple, str, bytes]):
      dest_addr, dest_port, *_ = address
      if dest_addr.startswith("127") or dest_addr == "localhost":
        self.set_proxy()
      return func(self, address)
    return _connect

  socks.socksocket.connect = wrap_connect(socks.socksocket.connect)