### Basic SOCKS Socket Usage with PySocks Source: https://github.com/anorov/pysocks/blob/master/README.md Illustrates the fundamental usage of PySocks' `socksocket` class to establish connections through SOCKS proxies. This class mirrors the standard `socket.socket` API. It requires the 'pysocks' library. The example shows setting SOCKS4, SOCKS5, and HTTP proxies, then performing a basic send/receive operation. ```python import socks # Initialize a SOCKS socket s = socks.socksocket() # Set proxy details (default port is 1080 for SOCKS5/4) s.set_proxy(socks.SOCKS5, "localhost") # Example for SOCKS4 with a specific port # s.set_proxy(socks.SOCKS4, "localhost", 4444) # Example for HTTP proxy # s.set_proxy(socks.HTTP, "5.5.5.5", 8888) # Connect to a remote host and port s.connect(("www.somesite.com", 80)) # Send data s.sendall("GET / HTTP/1.1\r\nHost: www.somesite.com\r\n\r\n") # Receive data response_data = s.recv(4096) print(response_data.decode('utf-8')) s.close() ``` -------------------------------- ### Proxy HTTP Traffic with Requests and PySocks Source: https://github.com/anorov/pysocks/blob/master/README.md Demonstrates how to configure HTTP requests to use SOCKS proxies via the 'requests' library, which utilizes PySocks internally. Ensure 'requests' and 'pysocks' are installed. This method is recommended for proxying HTTP traffic. ```python import requests url = "http://example.com" proxies = { "http": "socks5://proxyhostname:9050", "https": "socks5://proxyhostname:9050" } response = requests.get(url, proxies=proxies) print(response.text) ``` -------------------------------- ### Get Proxy Connection Information Source: https://context7.com/anorov/pysocks/llms.txt Demonstrates how to retrieve information about a proxy connection using the `get_proxy_peername()` method after a successful connection. This method returns the address and port of the proxy server itself. ```python import socks sock = socks.socksocket() sock.set_proxy(socks.SOCKS5, "proxy.example.com", 1080) sock.connect(("example.com", 80)) # Get proxy server address and port proxy_peer = sock.get_proxy_peername() print(f"Proxy server: {proxy_peer}") ``` -------------------------------- ### Get Bound Address and Destination Address using PySocks Source: https://context7.com/anorov/pysocks/llms.txt This snippet demonstrates how to retrieve the local address a SOCKS proxy socket is bound to and the address of the destination server it's connected to using PySocks. It assumes a 'sock' object has already been created and connected. ```python import socks # Assuming 'sock' is an initialized and connected socks.socksocket object # Example initialization (replace with your actual proxy details if needed): sock = socks.socksocket() sock.set_proxy(socks.SOCKS5, "127.0.0.1", 9050) # Example Tor proxy try: sock.connect(("example.com", 80)) # Get bound address at proxy proxy_sock = sock.get_proxy_sockname() print(f"Proxy bound address: {proxy_sock}") # Get destination server address destination = sock.get_peername() print(f"Destination: {destination}") finally: sock.close() ``` -------------------------------- ### Initialize SocksiPy Socket (Python) Source: https://github.com/anorov/pysocks/blob/master/README.md Demonstrates the basic instantiation of a SocksiPy socksocket object. This object mimics the standard socket interface but can be configured to use proxy servers. ```python import socks s = socks.socksocket() ``` -------------------------------- ### Create and Connect SOCKS Socket Source: https://context7.com/anorov/pysocks/llms.txt Demonstrates how to create a `socksocket` instance, configure proxy settings (SOCKS5 with optional authentication), and connect to a destination server through the proxy. ```APIDOC ## Create a SOCKS socket and connect through proxy ### Description Create a `socksocket` instance, configure proxy settings, and establish a connection to a destination server through the proxy. ### Method N/A (Illustrative Code) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import socks # Create a SOCKS socket s = socks.socksocket() # Configure SOCKS5 proxy (default port 1080) s.set_proxy(socks.SOCKS5, "localhost") # Or specify custom port and authentication s.set_proxy(socks.SOCKS5, "proxy.example.com", 1080, username="user", password="pass") # Connect to destination through proxy s.connect(("www.example.com", 80)) # Use like a regular socket s.sendall(b"GET / HTTP/1.1\r\nHost: www.example.com\r\n\r\n") response = s.recv(4096) print(response.decode()) # Clean up s.close() ``` ### Response #### Success Response (200) N/A (Illustrative Code) #### Response Example N/A ``` -------------------------------- ### Create and Connect SOCKS Socket via Proxy (Python) Source: https://context7.com/anorov/pysocks/llms.txt Demonstrates creating a `socksocket` instance, configuring SOCKS5 proxy settings (including optional authentication), connecting to a destination server through the proxy, sending data, receiving a response, and closing the socket. This is useful for establishing basic proxied connections. ```python import socks # Create a SOCKS socket s = socks.socksocket() # Configure SOCKS5 proxy (default port 1080) s.set_proxy(socks.SOCKS5, "localhost") # Or specify custom port and authentication s.set_proxy(socks.SOCKS5, "proxy.example.com", 1080, username="user", password="pass") # Connect to destination through proxy s.connect(("www.example.com", 80)) # Use like a regular socket s.sendall(b"GET / HTTP/1.1\r\nHost: www.example.com\r\n\r\n") response = s.recv(4096) print(response.decode()) # Clean up s.close() ``` -------------------------------- ### Create and Connect through HTTP Proxy with SSL Source: https://context7.com/anorov/pysocks/llms.txt Demonstrates creating a socket, setting an HTTP proxy, connecting through it, and then wrapping the connection with SSL for HTTPS. Includes basic error handling for HTTP proxy errors and ensures the socket is closed. ```python import socks import ssl sock = socks.socksocket() sock.set_proxy(socks.HTTP, "http-proxy.example.com", 8080, username="proxyuser", password="proxypass") try: # Connect through HTTP proxy sock.connect(("www.example.com", 443)) # Wrap with SSL for HTTPS context = ssl.create_default_context() secure_sock = context.wrap_socket(sock, server_hostname="www.example.com") secure_sock.sendall(b"GET / HTTP/1.1\r\nHost: www.example.com\r\n\r\n") response = secure_sock.recv(4096) print(response.decode()) except socks.HTTPError as e: print(f"HTTP proxy error: {e}") finally: sock.close() ``` -------------------------------- ### Create Connection with Timeout and Socket Options Source: https://context7.com/anorov/pysocks/llms.txt Shows how to use the `socks.create_connection` function for advanced proxy connections, including specifying timeouts, source binding, and custom socket options. ```APIDOC ## Create connection with timeout and socket options ### Description Use `create_connection` function for advanced proxy connections with timeout, source binding, and custom socket options. ### Method N/A (Illustrative Code) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import socks import socket # Create connection with timeout and TCP_NODELAY option sock = socks.create_connection( dest_pair=("example.com", 443), timeout=10.0, proxy_type=socks.SOCKS5, proxy_addr="proxy.example.com", proxy_port=1080, proxy_rdns=True, proxy_username="user", proxy_password="pass", socket_options=[(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)] ) try: sock.sendall(b"GET / HTTP/1.1\r\nHost: example.com\r\n\r\n") data = sock.recv(4096) print(data.decode()) except socket.timeout: print("Connection timed out") finally: sock.close() ``` ### Response #### Success Response (200) N/A (Illustrative Code) #### Response Example N/A ``` -------------------------------- ### Connect Through Proxy with SocksiPy (Python) Source: https://github.com/anorov/pysocks/blob/master/README.md Illustrates how to establish a network connection to a remote host and port using a SocksiPy socksocket object that has already been configured with proxy settings. If set_proxy() was not called, it behaves like a regular socket. ```python import socks s = socks.socksocket() s.set_proxy(socks.SOCKS5, "socks.example.com") s.connect(("www.sourceforge.net", 80)) ``` -------------------------------- ### Advanced Proxy Connection with Timeout and Options (Python) Source: https://context7.com/anorov/pysocks/llms.txt Demonstrates using the `socks.create_connection` function to establish a proxied connection with advanced configurations. This includes setting a connection timeout, binding to a specific source address, and applying custom socket options like `TCP_NODELAY`. It's suitable for scenarios requiring fine-grained control over the connection process. ```python import socks import socket # Create connection with timeout and TCP_NODELAY option sock = socks.create_connection( dest_pair=("example.com", 443), timeout=10.0, proxy_type=socks.SOCKS5, proxy_addr="proxy.example.com", proxy_port=1080, proxy_rdns=True, proxy_username="user", proxy_password="pass", socket_options=[(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)] ) try: sock.sendall(b"GET / HTTP/1.1\r\nHost: example.com\r\n\r\n") data = sock.recv(4096) print(data.decode()) except socket.timeout: print("Connection timed out") finally: sock.close() ``` -------------------------------- ### Monkeypatch Standard Library for Transparent Proxying Source: https://context7.com/anorov/pysocks/llms.txt Illustrates how to replace Python's standard `socket` module with `socks.socksocket` to transparently proxy all network connections from third-party libraries without code modifications. ```APIDOC ## Monkeypatch standard library for transparent proxying ### Description Replace Python's standard socket with socksocket to proxy all network connections from third-party libraries without code modifications. ### Method N/A (Illustrative Code) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import socket import socks import urllib.request # Save original socket (for cleanup) original_socket = socket.socket try: # Configure default proxy socks.set_default_proxy(socks.SOCKS5, "localhost", 9050) # Replace standard socket with socksocket socket.socket = socks.socksocket # Now all socket connections go through proxy response = urllib.request.urlopen("http://httpbin.org/ip") print(response.read().decode()) finally: # Restore original socket socket.socket = original_socket ``` ### Response #### Success Response (200) N/A (Illustrative Code) #### Response Example N/A ``` -------------------------------- ### Configure HTTP CONNECT Proxy Source: https://context7.com/anorov/pysocks/llms.txt Provides guidance on setting up an HTTP proxy connection using the CONNECT tunneling method, suitable for accessing HTTPS or other TCP services. ```APIDOC ## Configure HTTP CONNECT proxy ### Description Set up HTTP proxy connection using CONNECT tunneling method for accessing HTTPS or other TCP services. ### Method N/A (Illustrative Code) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import socks # Example usage for HTTP CONNECT proxy would follow similar patterns # as other proxy types, specifying socks.HTTP as proxy_type. # For instance: # http_sock = socks.socksocket() # http_sock.set_proxy(socks.HTTP, "proxy.example.com", 8080, # username="http_user", password="http_pass") # http_sock.connect(("www.target.com", 443)) ``` ### Response #### Success Response (200) N/A (Illustrative Code) #### Response Example N/A ``` -------------------------------- ### Set Global Default Proxy for Sockets (Python) Source: https://context7.com/anorov/pysocks/llms.txt Shows how to configure a default proxy for all `socksocket` instances created thereafter. This simplifies global proxying by eliminating the need to configure each socket individually. It also demonstrates how to retrieve the currently set default proxy configuration. ```python import socks # Set default proxy for all socksocket instances socks.set_default_proxy(socks.SOCKS5, "proxy.example.com", 1080, rdns=True, username="user", password="secret") # All new sockets will use this proxy automatically sock1 = socks.socksocket() sock1.connect(("example.com", 80)) sock2 = socks.socksocket() sock2.connect(("another-site.com", 443)) # Retrieve current default proxy proxy_config = socks.get_default_proxy() print(f"Default proxy: {proxy_config}") ``` -------------------------------- ### Monkeypatch Standard Library with Default Proxy (Python) Source: https://github.com/anorov/pysocks/blob/master/README.md This snippet demonstrates how to replace the default socket.socket with SocksiPy's socksocket to route all standard library network requests through a specified SOCKS5 proxy. Note that this approach is generally not recommended due to potential compatibility issues with other modules. ```python import urllib2 import socket import socks socks.set_default_proxy(socks.SOCKS5, "localhost") socket.socket = socks.socksocket ``` -------------------------------- ### Configure SOCKS4 Proxy with Remote DNS (Python) Source: https://context7.com/anorov/pysocks/llms.txt Illustrates setting up a SOCKS4 connection with the SOCKS4a extension enabled for remote DNS resolution. This is particularly useful in environments where local DNS might be restricted or monitored. Error handling for SOCKS4-specific and general proxy connection issues is included. ```python import socks # Create socket and configure SOCKS4 proxy sock = socks.socksocket() sock.set_proxy(socks.SOCKS4, "10.0.0.1", 1080, rdns=True, # Enable remote DNS (SOCKS4a) username="userid") # Connect to destination try: sock.connect(("example.com", 443)) print("Connected successfully") except socks.SOCKS4Error as e: print(f"SOCKS4 error: {e}") except socks.ProxyConnectionError as e: print(f"Proxy connection failed: {e}") print(f"Socket error: {e.socket_err}") finally: sock.close() ``` -------------------------------- ### Configure Proxy for SocksiPy Socket (Python) Source: https://github.com/anorov/pysocks/blob/master/README.md Shows how to set a specific proxy server (type, address, port, authentication) for a SocksiPy socksocket object before establishing a connection. Supported proxy types include SOCKS4, SOCKS5, and HTTP. ```python import socks s = socks.socksocket() s.set_proxy(socks.SOCKS5, "socks.example.com") # uses default port 1080 s.set_proxy(socks.SOCKS4, "socks.test.com", 1081) s.set_proxy(socks.SOCKS5, "user", "pass", "proxy.com", 1080, True) # Example with auth and rdns ``` -------------------------------- ### Configure HTTP CONNECT Proxy (Python) Source: https://context7.com/anorov/pysocks/llms.txt Provides a Python code snippet for setting up an HTTP proxy connection using the CONNECT tunneling method. This is essential for accessing HTTPS or other TCP-based services through an HTTP proxy server. ```python import socks ``` -------------------------------- ### Configure UDP Relay through SOCKS5 Source: https://context7.com/anorov/pysocks/llms.txt Provides a Python code snippet for setting up a UDP socket to relay datagrams through a SOCKS5 proxy server. It highlights that only SOCKS5 supports UDP and demonstrates binding, sending, and receiving UDP packets via the proxy. ```python import socks import socket # Create UDP socket sock = socks.socksocket(socket.AF_INET, socket.SOCK_DGRAM) # Configure SOCKS5 proxy (only SOCKS5 supports UDP) sock.set_proxy(socks.SOCKS5, "proxy.example.com", 1080, username="user", password="pass") try: # Bind triggers UDP association with proxy sock.bind(("", 0)) # Send UDP packet through proxy message = b"Hello via SOCKS5 UDP relay" sock.sendto(message, ("example.com", 53)) # Receive response data, addr = sock.recvfrom(4096) print(f"Received from {addr}: {data}") except socks.GeneralProxyError as e: print(f"UDP relay error: {e}") finally: sock.close() ``` -------------------------------- ### Setting Default Proxy Configuration in Python Source: https://github.com/anorov/pysocks/blob/master/README.md Demonstrates how to set default proxy configurations for new socket objects using `set_default_proxy`. This is useful for forcing third-party modules to use a specific proxy by overriding the default socket class. ```python import socket import urllib import socks # Set the default proxy to SOCKS5 with a specific server socks.set_default_proxy(socks.SOCKS5, "socks.example.com") # Override the default socket class to use pysocks socket.socket = socks.socksocket # Now, any socket created will use the default proxy settings # For example, opening a URL will go through the proxy try: response = urllib.urlopen("http://www.sourceforge.net/") print(response.read()) except Exception as e: print(f"An error occurred: {e}") ``` -------------------------------- ### Set Global Default Proxy Source: https://context7.com/anorov/pysocks/llms.txt Details on how to configure a default proxy that automatically applies to all new `socksocket` instances, simplifying global proxy settings. ```APIDOC ## Set global default proxy for all sockets ### Description Configure a default proxy that automatically applies to all new `socksocket` instances, enabling easy global proxy configuration. ### Method N/A (Illustrative Code) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import socks # Set default proxy for all socksocket instances socks.set_default_proxy(socks.SOCKS5, "proxy.example.com", 1080, rdns=True, username="user", password="secret") # All new sockets will use this proxy automatically sock1 = socks.socksocket() sock1.connect(("example.com", 80)) sock2 = socks.socksocket() sock2.connect(("another-site.com", 443)) # Retrieve current default proxy proxy_config = socks.get_default_proxy() print(f"Default proxy: {proxy_config}") ``` ### Response #### Success Response (200) N/A (Illustrative Code) #### Response Example N/A ``` -------------------------------- ### Configure SOCKS4 Proxy with Remote DNS Source: https://context7.com/anorov/pysocks/llms.txt Explains how to set up a SOCKS4 connection with the SOCKS4a extension for remote DNS resolution, which is useful when local DNS is restricted. ```APIDOC ## Configure SOCKS4 proxy with remote DNS resolution ### Description Set up a SOCKS4 connection with SOCKS4a extension for remote DNS resolution, useful when local DNS is restricted or monitored. ### Method N/A (Illustrative Code) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import socks # Create socket and configure SOCKS4 proxy sock = socks.socksocket() sock.set_proxy(socks.SOCKS4, "10.0.0.1", 1080, rdns=True, # Enable remote DNS (SOCKS4a) username="userid") # Connect to destination try: sock.connect(("example.com", 443)) print("Connected successfully") except socks.SOCKS4Error as e: print(f"SOCKS4 error: {e}") except socks.ProxyConnectionError as e: print(f"Proxy connection failed: {e}") print(f"Socket error: {e.socket_err}") finally: sock.close() ``` ### Response #### Success Response (200) N/A (Illustrative Code) #### Response Example N/A ``` -------------------------------- ### Transparent Proxying via Monkeypatching Standard Socket (Python) Source: https://context7.com/anorov/pysocks/llms.txt Explains and demonstrates how to replace Python's built-in `socket.socket` with `socks.socksocket` to transparently route all network connections through a configured proxy. This method allows third-party libraries that use the standard socket module to utilize the proxy without any code modifications. The original socket is saved and restored for cleanup. ```python import socket import socks import urllib.request # Save original socket (for cleanup) original_socket = socket.socket try: # Configure default proxy socks.set_default_proxy(socks.SOCKS5, "localhost", 9050) # Replace standard socket with socksocket socket.socket = socks.socksocket # Now all socket connections go through proxy response = urllib.request.urlopen("http://httpbin.org/ip") print(response.read().decode()) finally: # Restore original socket socket.socket = original_socket ``` -------------------------------- ### Use Urllib Handler for SOCKS Proxy Requests Source: https://context7.com/anorov/pysocks/llms.txt Shows how to configure the `urllib2` (or `urllib.request` in Python 3) library to use a SOCKS5 proxy without modifying the global socket behavior. It creates an opener with a `SocksiPyHandler` and then uses it to make HTTP requests. ```python import socks import sockshandler try: import urllib2 except ImportError: import urllib.request as urllib2 # Create opener with SOCKS5 handler opener = urllib2.build_opener( sockshandler.SocksiPyHandler( socks.SOCKS5, "localhost", 9050, rdns=True ) ) # Make HTTP request through proxy try: response = opener.open("http://httpbin.org/ip") print(f"Status: {response.getcode()}") print(f"Body: {response.read().decode()}") except urllib2.HTTPError as e: print(f"HTTP error: {e.code} {e.reason}") except urllib2.URLError as e: print(f"URL error: {e.reason}") ``` -------------------------------- ### Wrap Module for Selective Proxying (urllib.request) Source: https://context7.com/anorov/pysocks/llms.txt Demonstrates using `socks.wrap_module` to apply the default proxy settings to a specific module, in this case, `urllib.request`. This allows selective proxying without affecting the global socket behavior, ensuring other network operations are not proxied. ```python import socks import urllib.request # Set default proxy socks.set_default_proxy(socks.SOCKS5, "localhost", 9050) # Wrap only urllib module try: socks.wrap_module(urllib.request) # urllib.request now uses proxy response = urllib.request.urlopen("http://httpbin.org/ip") print(response.read().decode()) except socks.GeneralProxyError as e: print(f"No default proxy specified: {e}") ``` -------------------------------- ### Handle Proxy Errors with Exception Handling (SOCKS5) Source: https://context7.com/anorov/pysocks/llms.txt Illustrates comprehensive error handling for various proxy error types when using a SOCKS5 proxy. It specifically catches authentication failures, SOCKS5 protocol errors, connection errors, and general proxy errors, along with socket timeouts. ```python import socks import socket sock = socks.socksocket() sock.set_proxy(socks.SOCKS5, "proxy.example.com", 1080, username="user", password="wrongpass") sock.settimeout(5.0) try: sock.connect(("example.com", 80)) except socks.SOCKS5AuthError as e: print(f"Authentication failed: {e}") except socks.SOCKS5Error as e: print(f"SOCKS5 protocol error: {e}") except socks.ProxyConnectionError as e: print(f"Failed to connect to proxy: {e}") print(f"Underlying error: {e.socket_err}") except socks.GeneralProxyError as e: print(f"General proxy error: {e}") except socket.timeout: print("Connection timed out") finally: sock.close() ``` -------------------------------- ### Configure Socket Timeout and Blocking Mode Source: https://context7.com/anorov/pysocks/llms.txt Explains how to control socket timeout behavior for proxy connections using `settimeout()`. It shows setting a timeout before connection and changing it after a successful connection. Also demonstrates setting a socket to non-blocking mode. ```python import socks import socket sock = socks.socksocket() sock.set_proxy(socks.SOCKS5, "proxy.example.com", 1080) # Set timeout before connecting sock.settimeout(10.0) # 10 second timeout try: sock.connect(("example.com", 80)) # Change timeout after connection sock.settimeout(5.0) sock.sendall(b"GET / HTTP/1.1\r\nHost: example.com\r\n\r\n") data = sock.recv(4096) print(data.decode()) except socket.timeout: print("Operation timed out") finally: sock.close() # Non-blocking mode sock2 = socks.socksocket() sock2.set_proxy(socks.SOCKS5, "proxy.example.com", 1080) sock2.setblocking(False) # Non-blocking mode ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.