Typing stubs for PySocks

1.7.1.20260408 · active · verified Thu Apr 16

types-pysocks provides static type checking stubs for the PySocks library, enabling developers to write more robust and type-safe Python code when working with SOCKS proxy servers. PySocks itself is a Python module that offers a straightforward interface for routing network traffic through SOCKS proxies. The types-pysocks package, maintained by the Python community's typeshed project, keeps its stubs updated to reflect the PySocks API, with version 1.7.1.20260408 currently supporting Python 3.10 and newer. While the underlying PySocks library's direct development cadence might vary, the types-pysocks stubs are actively maintained.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to configure PySocks to route `urllib.request` traffic through a SOCKS5 proxy. It first sets a global default proxy and then 'monkey-patches' the standard `socket.socket` to use PySocks' `socksocket`, ensuring all subsequent socket operations (like those by `urllib.request`) go through the proxy. Ensure you have a running SOCKS proxy at the specified address and port.

import socks
import socket
import urllib.request
import os

# --- Configuration for SOCKS proxy ---
# Replace with your proxy details
PROXY_TYPE = socks.SOCKS5 # or socks.SOCKS4, socks.HTTP
PROXY_ADDR = os.environ.get('SOCKS_PROXY_ADDR', '127.0.0.1')
PROXY_PORT = int(os.environ.get('SOCKS_PROXY_PORT', 9050))
PROXY_USERNAME = os.environ.get('SOCKS_PROXY_USER', '')
PROXY_PASSWORD = os.environ.get('SOCKS_PROXY_PASS', '')

# Set up the default proxy for all subsequent socket connections
if PROXY_USERNAME and PROXY_PASSWORD:
    socks.set_default_proxy(PROXY_TYPE, PROXY_ADDR, PROXY_PORT, True, PROXY_USERNAME, PROXY_PASSWORD)
else:
    socks.set_default_proxy(PROXY_TYPE, PROXY_ADDR, PROXY_PORT)

# "Monkey-patch" the socket module to use PySocks
socket.socket = socks.socksocket

try:
    # Make a request that will now go through the SOCKS proxy
    print(f"Attempting to fetch external IP via proxy {PROXY_ADDR}:{PROXY_PORT}...")
    with urllib.request.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"Failed to connect via proxy: {e}")
except urllib.error.URLError as e:
    print(f"URL Error: {e.reason}")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

view raw JSON →