Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make wrap_module patch socket.getaddrinfo. #91

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,10 @@ To monkeypatch the entire standard library with a single default proxy:
import urllib2
import socket
import socks
import sys

socks.set_default_proxy(socks.SOCKS5, "localhost")
socket.socket = socks.socksocket
socks.wrap_module(sys.modules[__name__])

urllib2.urlopen("http://www.somesite.com/") # All requests will pass through the SOCKS proxy

Expand Down
12 changes: 11 additions & 1 deletion socks.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@
PRINTABLE_PROXY_TYPES = dict(zip(PROXY_TYPES.values(), PROXY_TYPES.keys()))

_orgsocket = _orig_socket = socket.socket

_orig_getaddrinfo = socket.getaddrinfo

def set_self_blocking(function):

Expand Down Expand Up @@ -188,6 +188,15 @@ def get_default_proxy():

getdefaultproxy = get_default_proxy

# https://web.archive.org/web/20161211104525/http://fitblip.pub/2012/11/13/proxying-dns-with-python/
def getaddrinfo(*args):
(proxy_type, proxy_addr, proxy_port, rdns, username,
password) = get_default_proxy()

if proxy_type is not None and rdns:
return [(socket.AF_INET, socket.SOCK_STREAM, 6, '', (args[0], args[1]))]

return _orig_getaddrinfo(*args)

def wrap_module(module):
"""Attempts to replace a module's socket library with a SOCKS socket.
Expand All @@ -196,6 +205,7 @@ def wrap_module(module):
only work on modules that import socket directly into the namespace;
most of the Python Standard Library falls into this category."""
if socksocket.default_proxy:
module.socket.getaddrinfo = getaddrinfo
module.socket.socket = socksocket
else:
raise GeneralProxyError("No default proxy specified")
Expand Down