Proxy (SOCKS4, SOCKS5, HTTP CONNECT) client for Python
—
Core types, exceptions, and utility functions used across all proxy implementations. This module provides the fundamental building blocks for proxy connectivity including protocol types, error handling, and URL parsing.
Defines the supported proxy protocol types.
from enum import Enum
class ProxyType(Enum):
SOCKS4 = 1
SOCKS5 = 2
HTTP = 3Usage:
from python_socks import ProxyType
# Specify proxy type when creating proxy instances
proxy_type = ProxyType.SOCKS5Comprehensive error handling for proxy operations.
class ProxyError(Exception):
def __init__(self, message, error_code=None): ...
class ProxyTimeoutError(TimeoutError):
pass
class ProxyConnectionError(OSError):
passProxyError Details:
error_code attribute provides protocol-specific error informationProxyTimeoutError Details:
TimeoutError for compatibilityProxyConnectionError Details:
OSError providing errno and strerror attributesUsage:
from python_socks import ProxyError, ProxyTimeoutError, ProxyConnectionError
from python_socks.sync import Proxy
try:
proxy = Proxy.from_url('socks5://127.0.0.1:1080')
sock = proxy.connect('example.com', 80, timeout=10)
except ProxyConnectionError as e:
print(f"Could not connect to proxy: {e}")
except ProxyTimeoutError as e:
print(f"Proxy connection timed out: {e}")
except ProxyError as e:
print(f"Proxy error: {e}, error_code: {e.error_code}")Parses proxy URLs to extract connection parameters.
from typing import Tuple, Optional
def parse_proxy_url(url: str) -> Tuple[ProxyType, str, int, Optional[str], Optional[str]]:
"""
Parse proxy URL into components.
Args:
url: Proxy URL in format: scheme://[username:password@]host:port
Returns:
Tuple containing (proxy_type, host, port, username, password)
Raises:
ValueError: If URL format is invalid or unsupported scheme
"""
...Supported URL Formats:
socks4://host:portsocks5://host:porthttp://host:portsocks4://username:password@host:portsocks5://username:password@host:porthttp://username:password@host:portUsage:
from python_socks import parse_proxy_url, ProxyType
# Parse complete proxy URL
proxy_type, host, port, username, password = parse_proxy_url(
'socks5://user:pass@127.0.0.1:1080'
)
assert proxy_type == ProxyType.SOCKS5
assert host == '127.0.0.1'
assert port == 1080
assert username == 'user'
assert password == 'pass'
# Parse URL without credentials
proxy_type, host, port, username, password = parse_proxy_url(
'http://proxy.example.com:8080'
)
assert proxy_type == ProxyType.HTTP
assert host == 'proxy.example.com'
assert port == 8080
assert username == ''
assert password == ''IP address validation utilities (internal but available).
from typing import Union
def is_ipv4_address(host: Union[str, bytes]) -> bool:
"""Check if host is valid IPv4 address."""
...
def is_ipv6_address(host: Union[str, bytes]) -> bool:
"""Check if host is valid IPv6 address."""
...
def is_ip_address(host: Union[str, bytes]) -> bool:
"""Check if host is valid IP address (IPv4 or IPv6)."""
...Usage:
from python_socks._helpers import is_ipv4_address, is_ipv6_address, is_ip_address
# IPv4 validation
assert is_ipv4_address('192.168.1.1') == True
assert is_ipv4_address('256.1.1.1') == False
# IPv6 validation
assert is_ipv6_address('::1') == True
assert is_ipv6_address('2001:db8::1') == True
# General IP validation
assert is_ip_address('127.0.0.1') == True
assert is_ip_address('::1') == True
assert is_ip_address('example.com') == False__title__: str = 'python-socks'
__version__: str = '2.7.2'Usage:
import python_socks
print(f"Using {python_socks.__title__} version {python_socks.__version__}")from python_socks import ProxyError, ProxyTimeoutError, ProxyConnectionError
from python_socks.sync import Proxy
def connect_with_retry(proxy_url: str, dest_host: str, dest_port: int, max_retries: int = 3):
"""Connect through proxy with retry logic."""
for attempt in range(max_retries):
try:
proxy = Proxy.from_url(proxy_url)
return proxy.connect(dest_host, dest_port, timeout=30)
except ProxyConnectionError:
if attempt == max_retries - 1:
raise
print(f"Retry attempt {attempt + 1}")
except ProxyTimeoutError:
if attempt == max_retries - 1:
raise
print(f"Timeout on attempt {attempt + 1}")
except ProxyError as e:
# Don't retry on authentication or protocol errors
print(f"Proxy error: {e} (code: {e.error_code})")
raiseProxyError instances may include protocol-specific error codes:
SOCKS4 Error Codes:
SOCKS5 Error Codes:
HTTP CONNECT Error Codes:
Install with Tessl CLI
npx tessl i tessl/pypi-python-socks