PySocks

1.7.1 · active · verified Sat Mar 28

PySocks is a Python SOCKS client module that enables applications to route their network traffic through SOCKS proxy servers. It acts as a robust, modern fork of SocksiPy, offering a drop-in replacement for Python's standard `socket` module with added proxy functionalities. It is also a key underlying dependency for SOCKS proxy support in the popular `requests` library.

Warnings

Install

Imports

Quickstart

This example demonstrates how to configure PySocks to route all outgoing `socket` traffic through a SOCKS proxy by monkey-patching the standard `socket.socket`. It attempts to fetch the external IP address using `urllib.request` which will then use the proxified socket. Proxy details are loaded from environment variables for flexibility.

import socks
import socket
import os
from urllib.request import urlopen

# Configure proxy details from environment variables or use defaults
proxy_type = socks.SOCKS5
proxy_addr = os.environ.get('SOCKS_PROXY_HOST', '127.0.0.1')
proxy_port = int(os.environ.get('SOCKS_PROXY_PORT', 9050))

try:
    # Set a default SOCKS proxy for all socket connections
    socks.set_default_proxy(proxy_type, proxy_addr, proxy_port)
    # Monkeypatch the standard socket module to use PySocks
    socket.socket = socks.socksocket

    print(f"Attempting to connect via SOCKS{proxy_type} proxy at {proxy_addr}:{proxy_port}")
    # Make a request using urllib, which now uses the proxified socket
    with urlopen('http://icanhazip.com') as response:
        external_ip = response.read().decode('utf-8').strip()
        print(f"External IP (via proxy): {external_ip}")
except socks.ProxyError as e:
    print(f"Proxy connection failed: {e}. Check proxy settings and availability.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

view raw JSON →