0
# Core API
1
2
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.
3
4
## Capabilities
5
6
### Proxy Type Enumeration
7
8
Defines the supported proxy protocol types.
9
10
```python { .api }
11
from enum import Enum
12
13
class ProxyType(Enum):
14
SOCKS4 = 1
15
SOCKS5 = 2
16
HTTP = 3
17
```
18
19
**Usage:**
20
21
```python
22
from python_socks import ProxyType
23
24
# Specify proxy type when creating proxy instances
25
proxy_type = ProxyType.SOCKS5
26
```
27
28
### Exception Classes
29
30
Comprehensive error handling for proxy operations.
31
32
```python { .api }
33
class ProxyError(Exception):
34
def __init__(self, message, error_code=None): ...
35
36
class ProxyTimeoutError(TimeoutError):
37
pass
38
39
class ProxyConnectionError(OSError):
40
pass
41
```
42
43
**ProxyError Details:**
44
- Base exception for all proxy-related errors
45
- Optional `error_code` attribute provides protocol-specific error information
46
- Raised when proxy server returns error responses or authentication fails
47
48
**ProxyTimeoutError Details:**
49
- Raised when proxy operations exceed specified timeout
50
- Inherits from built-in `TimeoutError` for compatibility
51
52
**ProxyConnectionError Details:**
53
- Raised when connection to proxy server fails
54
- Inherits from `OSError` providing errno and strerror attributes
55
- Common causes: network unreachable, connection refused, DNS resolution failure
56
57
**Usage:**
58
59
```python
60
from python_socks import ProxyError, ProxyTimeoutError, ProxyConnectionError
61
from python_socks.sync import Proxy
62
63
try:
64
proxy = Proxy.from_url('socks5://127.0.0.1:1080')
65
sock = proxy.connect('example.com', 80, timeout=10)
66
except ProxyConnectionError as e:
67
print(f"Could not connect to proxy: {e}")
68
except ProxyTimeoutError as e:
69
print(f"Proxy connection timed out: {e}")
70
except ProxyError as e:
71
print(f"Proxy error: {e}, error_code: {e.error_code}")
72
```
73
74
### URL Parsing
75
76
Parses proxy URLs to extract connection parameters.
77
78
```python { .api }
79
from typing import Tuple, Optional
80
81
def parse_proxy_url(url: str) -> Tuple[ProxyType, str, int, Optional[str], Optional[str]]:
82
"""
83
Parse proxy URL into components.
84
85
Args:
86
url: Proxy URL in format: scheme://[username:password@]host:port
87
88
Returns:
89
Tuple containing (proxy_type, host, port, username, password)
90
91
Raises:
92
ValueError: If URL format is invalid or unsupported scheme
93
"""
94
...
95
```
96
97
**Supported URL Formats:**
98
- `socks4://host:port`
99
- `socks5://host:port`
100
- `http://host:port`
101
- `socks4://username:password@host:port`
102
- `socks5://username:password@host:port`
103
- `http://username:password@host:port`
104
105
**Usage:**
106
107
```python
108
from python_socks import parse_proxy_url, ProxyType
109
110
# Parse complete proxy URL
111
proxy_type, host, port, username, password = parse_proxy_url(
112
'socks5://user:pass@127.0.0.1:1080'
113
)
114
115
assert proxy_type == ProxyType.SOCKS5
116
assert host == '127.0.0.1'
117
assert port == 1080
118
assert username == 'user'
119
assert password == 'pass'
120
121
# Parse URL without credentials
122
proxy_type, host, port, username, password = parse_proxy_url(
123
'http://proxy.example.com:8080'
124
)
125
126
assert proxy_type == ProxyType.HTTP
127
assert host == 'proxy.example.com'
128
assert port == 8080
129
assert username == ''
130
assert password == ''
131
```
132
133
### Helper Functions
134
135
IP address validation utilities (internal but available).
136
137
```python { .api }
138
from typing import Union
139
140
def is_ipv4_address(host: Union[str, bytes]) -> bool:
141
"""Check if host is valid IPv4 address."""
142
...
143
144
def is_ipv6_address(host: Union[str, bytes]) -> bool:
145
"""Check if host is valid IPv6 address."""
146
...
147
148
def is_ip_address(host: Union[str, bytes]) -> bool:
149
"""Check if host is valid IP address (IPv4 or IPv6)."""
150
...
151
```
152
153
**Usage:**
154
155
```python
156
from python_socks._helpers import is_ipv4_address, is_ipv6_address, is_ip_address
157
158
# IPv4 validation
159
assert is_ipv4_address('192.168.1.1') == True
160
assert is_ipv4_address('256.1.1.1') == False
161
162
# IPv6 validation
163
assert is_ipv6_address('::1') == True
164
assert is_ipv6_address('2001:db8::1') == True
165
166
# General IP validation
167
assert is_ip_address('127.0.0.1') == True
168
assert is_ip_address('::1') == True
169
assert is_ip_address('example.com') == False
170
```
171
172
## Constants
173
174
### Package Metadata
175
176
```python { .api }
177
__title__: str = 'python-socks'
178
__version__: str = '2.7.2'
179
```
180
181
**Usage:**
182
183
```python
184
import python_socks
185
186
print(f"Using {python_socks.__title__} version {python_socks.__version__}")
187
```
188
189
## Error Handling Patterns
190
191
### Common Exception Handling
192
193
```python
194
from python_socks import ProxyError, ProxyTimeoutError, ProxyConnectionError
195
from python_socks.sync import Proxy
196
197
def connect_with_retry(proxy_url: str, dest_host: str, dest_port: int, max_retries: int = 3):
198
"""Connect through proxy with retry logic."""
199
for attempt in range(max_retries):
200
try:
201
proxy = Proxy.from_url(proxy_url)
202
return proxy.connect(dest_host, dest_port, timeout=30)
203
except ProxyConnectionError:
204
if attempt == max_retries - 1:
205
raise
206
print(f"Retry attempt {attempt + 1}")
207
except ProxyTimeoutError:
208
if attempt == max_retries - 1:
209
raise
210
print(f"Timeout on attempt {attempt + 1}")
211
except ProxyError as e:
212
# Don't retry on authentication or protocol errors
213
print(f"Proxy error: {e} (code: {e.error_code})")
214
raise
215
```
216
217
### Protocol-Specific Error Codes
218
219
ProxyError instances may include protocol-specific error codes:
220
221
**SOCKS4 Error Codes:**
222
- 90: Request rejected or failed
223
- 91: Connection rejected (identd not running)
224
- 92: Connection rejected (identd cannot confirm user ID)
225
- 93: Connection rejected (invalid user ID)
226
227
**SOCKS5 Error Codes:**
228
- 1: General SOCKS server failure
229
- 2: Connection not allowed by ruleset
230
- 3: Network unreachable
231
- 4: Host unreachable
232
- 5: Connection refused
233
- 6: TTL expired
234
- 7: Command not supported
235
- 8: Address type not supported
236
237
**HTTP CONNECT Error Codes:**
238
- HTTP status codes (e.g., 407 for proxy authentication required)