0
# PySocks
1
2
PySocks is a modern Python SOCKS proxy client library that serves as a drop-in replacement for the standard socket module, enabling seamless SOCKS proxy integration for any socket-based application. The library supports SOCKS4 and SOCKS5 protocols with comprehensive TCP support and partial UDP support, making it suitable for a wide range of network applications requiring proxy connectivity.
3
4
## Package Information
5
6
- **Package Name**: PySocks
7
- **Package Type**: pypi
8
- **Language**: Python
9
- **Installation**: `pip install pysocks`
10
- **Python Support**: 2.7, 3.4+
11
12
## Core Imports
13
14
```python
15
import socks
16
```
17
18
For urllib2/urllib.request integration:
19
20
```python
21
import sockshandler
22
```
23
24
## Basic Usage
25
26
```python
27
import socks
28
29
# Create a SOCKS-enabled socket
30
s = socks.socksocket()
31
32
# Configure SOCKS5 proxy with authentication
33
s.set_proxy(socks.SOCKS5, "localhost", 1080, username="user", password="pass")
34
35
# Use like a regular socket
36
s.connect(("www.example.com", 80))
37
s.sendall(b"GET / HTTP/1.1\r\nHost: www.example.com\r\n\r\n")
38
response = s.recv(4096)
39
s.close()
40
41
# Alternative: Use create_connection helper
42
try:
43
conn = socks.create_connection(
44
("www.example.com", 80),
45
proxy_type=socks.SOCKS5,
46
proxy_addr="localhost",
47
proxy_port=1080
48
)
49
conn.sendall(b"GET / HTTP/1.1\r\nHost: www.example.com\r\n\r\n")
50
response = conn.recv(4096)
51
conn.close()
52
except socks.ProxyError as e:
53
print(f"Proxy error: {e}")
54
```
55
56
## Architecture
57
58
PySocks implements a socket-compatible interface that transparently handles proxy negotiations:
59
60
- **socksocket**: Main socket class inheriting from standard socket, adding proxy functionality
61
- **Proxy negotiators**: Protocol-specific handlers for SOCKS4, SOCKS5, and HTTP CONNECT
62
- **Error hierarchy**: Comprehensive exception system for different proxy error scenarios
63
- **Module integration**: Optional urllib2/urllib.request handler for web requests
64
65
The library uses the strategy pattern for different proxy protocols and maintains full socket API compatibility.
66
67
## Capabilities
68
69
### Core SOCKS Socket Operations
70
71
Primary SOCKS proxy functionality including socket creation, proxy configuration, connection establishment, and data transfer. Supports SOCKS4, SOCKS5, and HTTP CONNECT protocols with authentication.
72
73
```python { .api }
74
class socksocket:
75
def __init__(self, family=socket.AF_INET, type=socket.SOCK_STREAM, proto=0): ...
76
def set_proxy(self, proxy_type=None, addr=None, port=None, rdns=True, username=None, password=None): ...
77
def setproxy(self, *args, **kwargs): ... # Legacy alias for set_proxy
78
def connect(self, dest_pair): ...
79
def connect_ex(self, dest_pair) -> int: ... # Returns error code instead of raising
80
def bind(self, address): ...
81
def send(self, bytes, flags=0) -> int: ...
82
def sendto(self, bytes, *args, **kwargs) -> int: ...
83
def recv(self, bufsize, flags=0) -> bytes: ...
84
def recvfrom(self, bufsize, flags=0) -> tuple[bytes, tuple[str, int]]: ...
85
def close(self): ...
86
def settimeout(self, timeout): ...
87
def gettimeout(self) -> float | None: ...
88
def setblocking(self, flag: bool): ...
89
def get_proxy_sockname(self) -> tuple[str, int]: ...
90
def getproxysockname(self) -> tuple[str, int]: ... # Legacy alias
91
def get_proxy_peername(self) -> tuple[str, int]: ...
92
def getproxypeername(self) -> tuple[str, int]: ... # Legacy alias
93
def get_peername(self) -> tuple[str, int]: ...
94
def getpeername(self) -> tuple[str, int]: ... # Override of socket.getpeername
95
96
def create_connection(dest_pair, timeout=None, source_address=None, proxy_type=None, proxy_addr=None, proxy_port=None, proxy_rdns=True, proxy_username=None, proxy_password=None, socket_options=None) -> socksocket: ...
97
```
98
99
### Global Proxy Management
100
101
System-wide proxy configuration and module monkey-patching functionality for applying SOCKS proxy settings to existing code without modification.
102
103
```python { .api }
104
def set_default_proxy(proxy_type=None, addr=None, port=None, rdns=True, username=None, password=None): ...
105
def setdefaultproxy(*args, **kwargs): ... # Legacy alias for set_default_proxy
106
def get_default_proxy() -> ProxySettings: ...
107
def getdefaultproxy() -> ProxySettings: ... # Legacy alias for get_default_proxy
108
def wrap_module(module): ...
109
def wrapmodule(module): ... # Legacy alias for wrap_module
110
```
111
112
### urllib Integration
113
114
Integration with urllib2 and urllib.request for making HTTP/HTTPS requests through SOCKS proxies, providing a handler that can be used with urllib2.build_opener().
115
116
```python { .api }
117
class SocksiPyHandler:
118
def __init__(self, proxytype, proxyaddr, proxyport=None, rdns=True, username=None, password=None): ...
119
def http_open(self, req): ...
120
def https_open(self, req): ...
121
```
122
123
[urllib Integration](./urllib-integration.md)
124
125
## Proxy Types
126
127
```python { .api }
128
PROXY_TYPE_SOCKS4: int # SOCKS4 proxy type (value: 1)
129
SOCKS4: int # Alias for PROXY_TYPE_SOCKS4
130
131
PROXY_TYPE_SOCKS5: int # SOCKS5 proxy type (value: 2)
132
SOCKS5: int # Alias for PROXY_TYPE_SOCKS5
133
134
PROXY_TYPE_HTTP: int # HTTP CONNECT proxy type (value: 3)
135
HTTP: int # Alias for PROXY_TYPE_HTTP
136
137
# Constant dictionaries
138
PROXY_TYPES: dict[str, int] # Maps proxy type names to values
139
PRINTABLE_PROXY_TYPES: dict[int, str] # Maps proxy type values to names
140
DEFAULT_PORTS: dict[int, int] # Default ports for each proxy type {SOCKS4: 1080, SOCKS5: 1080, HTTP: 8080}
141
SOCKS4_ERRORS: dict[int, str] # SOCKS4 error code to message mappings
142
SOCKS5_ERRORS: dict[int, str] # SOCKS5 error code to message mappings
143
144
# Package version
145
__version__: str # Package version string
146
```
147
148
## Exception Types
149
150
```python { .api }
151
class ProxyError(IOError):
152
"""Base proxy error class."""
153
def __init__(self, msg: str, socket_err=None): ...
154
155
class GeneralProxyError(ProxyError):
156
"""General proxy errors."""
157
pass
158
159
class ProxyConnectionError(ProxyError):
160
"""Proxy connection errors."""
161
pass
162
163
class SOCKS5AuthError(ProxyError):
164
"""SOCKS5 authentication errors."""
165
pass
166
167
class SOCKS5Error(ProxyError):
168
"""SOCKS5 protocol errors."""
169
pass
170
171
class SOCKS4Error(ProxyError):
172
"""SOCKS4 protocol errors."""
173
pass
174
175
class HTTPError(ProxyError):
176
"""HTTP proxy errors."""
177
pass
178
```
179
180
## Type Definitions
181
182
```python { .api }
183
ProxySettings = tuple[
184
int | None, # proxy_type: SOCKS4, SOCKS5, HTTP, or None
185
str | None, # addr: proxy server address
186
int | None, # port: proxy server port
187
bool, # rdns: remote DNS resolution flag
188
bytes | None, # username: authentication username
189
bytes | None # password: authentication password
190
]
191
192
DestinationPair = tuple[str, int] # (hostname/IP, port)
193
SocketOptions = list[tuple[int, int, int]] # [(level, optname, value), ...]
194
```