CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-python-socks

Proxy (SOCKS4, SOCKS5, HTTP CONNECT) client for Python

Pending
Overview
Eval results
Files

core-api.mddocs/

Core API

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.

Capabilities

Proxy Type Enumeration

Defines the supported proxy protocol types.

from enum import Enum

class ProxyType(Enum):
    SOCKS4 = 1
    SOCKS5 = 2
    HTTP = 3

Usage:

from python_socks import ProxyType

# Specify proxy type when creating proxy instances
proxy_type = ProxyType.SOCKS5

Exception Classes

Comprehensive error handling for proxy operations.

class ProxyError(Exception):
    def __init__(self, message, error_code=None): ...
    
class ProxyTimeoutError(TimeoutError):
    pass
    
class ProxyConnectionError(OSError):
    pass

ProxyError Details:

  • Base exception for all proxy-related errors
  • Optional error_code attribute provides protocol-specific error information
  • Raised when proxy server returns error responses or authentication fails

ProxyTimeoutError Details:

  • Raised when proxy operations exceed specified timeout
  • Inherits from built-in TimeoutError for compatibility

ProxyConnectionError Details:

  • Raised when connection to proxy server fails
  • Inherits from OSError providing errno and strerror attributes
  • Common causes: network unreachable, connection refused, DNS resolution failure

Usage:

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}")

URL Parsing

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:port
  • socks5://host:port
  • http://host:port
  • socks4://username:password@host:port
  • socks5://username:password@host:port
  • http://username:password@host:port

Usage:

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 == ''

Helper Functions

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

Constants

Package Metadata

__title__: str = 'python-socks'
__version__: str = '2.7.2'

Usage:

import python_socks

print(f"Using {python_socks.__title__} version {python_socks.__version__}")

Error Handling Patterns

Common Exception Handling

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})")
            raise

Protocol-Specific Error Codes

ProxyError instances may include protocol-specific error codes:

SOCKS4 Error Codes:

  • 90: Request rejected or failed
  • 91: Connection rejected (identd not running)
  • 92: Connection rejected (identd cannot confirm user ID)
  • 93: Connection rejected (invalid user ID)

SOCKS5 Error Codes:

  • 1: General SOCKS server failure
  • 2: Connection not allowed by ruleset
  • 3: Network unreachable
  • 4: Host unreachable
  • 5: Connection refused
  • 6: TTL expired
  • 7: Command not supported
  • 8: Address type not supported

HTTP CONNECT Error Codes:

  • HTTP status codes (e.g., 407 for proxy authentication required)

Install with Tessl CLI

npx tessl i tessl/pypi-python-socks

docs

async-api.md

core-api.md

index.md

sync-api.md

v2-api.md

tile.json