CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-pysocks

A Python SOCKS client module providing drop-in replacement for the standard socket module to enable seamless SOCKS proxy integration.

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

urllib-integration.mddocs/

urllib Integration (sockshandler)

HTTP and HTTPS request handling through SOCKS proxies using urllib2 and urllib.request. This module provides handler classes that integrate with Python's urllib system to route web requests through SOCKS proxies.

Capabilities

HTTP Handler

Creates urllib2/urllib.request handlers for making HTTP and HTTPS requests through SOCKS proxies, with automatic fallback handling for SOCKS4 servers that don't support remote DNS resolution.

class SocksiPyHandler:
    """urllib2/urllib.request handler for SOCKS proxies."""
    
    def __init__(self, proxytype: int, proxyaddr: str, proxyport: int = None, rdns: bool = True, username: str = None, password: str = None, **kwargs):
        """
        Initialize SOCKS proxy handler.
        
        Parameters:
        - proxytype: socks.SOCKS4, socks.SOCKS5, or socks.HTTP
        - proxyaddr: proxy server hostname or IP address
        - proxyport: proxy server port (defaults: 1080 for SOCKS, 8080 for HTTP)
        - rdns: whether to resolve DNS remotely (True) or locally (False)
        - username: proxy authentication username (SOCKS5 and SOCKS4 userid)
        - password: proxy authentication password (SOCKS5 only)
        - **kwargs: additional arguments passed to connection classes
        """
    
    def http_open(self, req) -> urllib2.HTTPResponse:
        """Handle HTTP requests through the SOCKS proxy."""
    
    def https_open(self, req) -> urllib2.HTTPResponse:
        """Handle HTTPS requests through the SOCKS proxy."""

Connection Classes

Low-level HTTP and HTTPS connection classes that handle the actual proxy tunneling for urllib2/urllib.request handlers.

class SocksiPyConnection:
    """HTTP connection through SOCKS proxy."""
    
    def __init__(self, proxytype: int, proxyaddr: str, proxyport: int = None, rdns: bool = True, username: str = None, password: str = None, *args, **kwargs):
        """Initialize HTTP connection with proxy settings."""
    
    def connect(self):
        """Establish HTTP connection through SOCKS proxy."""

class SocksiPyConnectionS:
    """HTTPS connection through SOCKS proxy."""
    
    def __init__(self, proxytype: int, proxyaddr: str, proxyport: int = None, rdns: bool = True, username: str = None, password: str = None, *args, **kwargs):
        """Initialize HTTPS connection with proxy settings."""
    
    def connect(self):
        """Establish HTTPS connection through SOCKS proxy with SSL wrapping."""

Utility Functions

Helper functions for IP address validation and dictionary merging used internally by the connection classes.

def is_ip(s: str) -> bool:
    """
    Check if string is a valid IPv4 or IPv6 address.
    
    Parameters:
    - s: string to check
    
    Returns:
    bool: True if valid IP address, False otherwise
    """

def merge_dict(a: dict, b: dict) -> dict:
    """
    Merge two dictionaries, with values from b taking precedence.
    
    Parameters:
    - a: base dictionary
    - b: dictionary with override values
    
    Returns:
    dict: merged dictionary
    """

Usage Examples

Basic urllib2/urllib.request Integration

import urllib2
import socks
import sockshandler

# Create SOCKS5 proxy handler
handler = sockshandler.SocksiPyHandler(
    socks.SOCKS5, 
    "localhost", 
    9050,
    username="user",
    password="pass"
)

# Build opener with the handler
opener = urllib2.build_opener(handler)

# Make requests through the proxy
response = opener.open("http://httpbin.org/ip")
print(response.read().decode())

response = opener.open("https://httpbin.org/ip")
print(response.read().decode())

Python 3 urllib.request Integration

import urllib.request
import socks
import sockshandler

# Create SOCKS5 proxy handler  
handler = sockshandler.SocksiPyHandler(socks.SOCKS5, "localhost", 9050)

# Build opener
opener = urllib.request.build_opener(handler)

# Install as global default (optional)
urllib.request.install_opener(opener)

# Make requests
with urllib.request.urlopen("http://example.com") as response:
    content = response.read()

SOCKS4 with Automatic Fallback

import urllib2
import socks
import sockshandler

# Handler automatically handles SOCKS4 servers that don't support remote DNS
handler = sockshandler.SocksiPyHandler(
    socks.SOCKS4,
    "socks4-proxy.example.com",
    1080,
    rdns=True  # Will fallback to local DNS if server doesn't support remote
)

opener = urllib2.build_opener(handler)
response = opener.open("http://example.com")

Error Handling

The handler classes automatically handle common SOCKS4 compatibility issues:

  • SOCKS4 Remote DNS Fallback: If a SOCKS4 server returns error 0x5b and remote DNS was requested, automatically retries with local DNS resolution
  • Proxy Error Propagation: All SOCKS errors (SOCKS4Error, SOCKS5Error, etc.) are propagated up through urllib2's exception system
  • SSL Certificate Validation: HTTPS connections properly validate SSL certificates and handle SSL errors

Global State

socks4_no_rdns: set[str]  # Set of SOCKS4 proxy addresses that don't support remote DNS

This global set tracks SOCKS4 proxy servers that have been determined not to support remote DNS resolution, enabling automatic fallback behavior for subsequent connections.

Install with Tessl CLI

npx tessl i tessl/pypi-pysocks

docs

index.md

urllib-integration.md

tile.json