1PySocks
2=======
3
4PySocks lets you send traffic through SOCKS and HTTP proxy servers. It is a modern fork of [SocksiPy](http://socksipy.sourceforge.net/) with bug fixes and extra features.
5
6Acts as a drop-in replacement to the socket module. Seamlessly configure SOCKS proxies for any socket object by calling `socket_object.set_proxy()`.
7
8----------------
9
10Features
11========
12
13* SOCKS proxy client for Python 2.7 and 3.4+
14* TCP supported
15* UDP mostly supported (issues may occur in some edge cases)
16* HTTP proxy client included but not supported or recommended (you should use urllib2's or requests' own HTTP proxy interface)
17* urllib2 handler included. `pip install` / `setup.py install` will automatically install the `sockshandler` module.
18
19Installation
20============
21
22    pip install PySocks
23
24Or download the tarball / `git clone` and...
25
26    python setup.py install
27
28These will install both the `socks` and `sockshandler` modules.
29
30Alternatively, include just `socks.py` in your project.
31
32--------------------------------------------
33
34*Warning:* PySocks/SocksiPy only supports HTTP proxies that use CONNECT tunneling. Certain HTTP proxies may not work with this library. If you wish to use HTTP (not SOCKS) proxies, it is recommended that you rely on your HTTP client's native proxy support (`proxies` dict for `requests`, or `urllib2.ProxyHandler` for `urllib2`) instead.
35
36--------------------------------------------
37
38Usage
39=====
40
41## socks.socksocket ##
42
43    import socks
44
45    s = socks.socksocket() # Same API as socket.socket in the standard lib
46
47    s.set_proxy(socks.SOCKS5, "localhost") # SOCKS4 and SOCKS5 use port 1080 by default
48    # Or
49    s.set_proxy(socks.SOCKS4, "localhost", 4444)
50    # Or
51    s.set_proxy(socks.HTTP, "5.5.5.5", 8888)
52
53    # Can be treated identical to a regular socket object
54    s.connect(("www.somesite.com", 80))
55    s.sendall("GET / HTTP/1.1 ...")
56    print s.recv(4096)
57
58## Monkeypatching ##
59
60To monkeypatch the entire standard library with a single default proxy:
61
62    import urllib2
63    import socket
64    import socks
65
66    socks.set_default_proxy(socks.SOCKS5, "localhost")
67    socket.socket = socks.socksocket
68
69    urllib2.urlopen("http://www.somesite.com/") # All requests will pass through the SOCKS proxy
70
71Note that monkeypatching may not work for all standard modules or for all third party modules, and generally isn't recommended. Monkeypatching is usually an anti-pattern in Python.
72
73## urllib2 Handler ##
74
75Example use case with the `sockshandler` urllib2 handler. Note that you must import both `socks` and `sockshandler`, as the handler is its own module separate from PySocks. The module is included in the PyPI package.
76
77    import urllib2
78    import socks
79    from sockshandler import SocksiPyHandler
80
81    opener = urllib2.build_opener(SocksiPyHandler(socks.SOCKS5, "127.0.0.1", 9050))
82    print opener.open("http://www.somesite.com/") # All requests made by the opener will pass through the SOCKS proxy
83
84--------------------------------------------
85
86Original SocksiPy README attached below, amended to reflect API changes.
87
88--------------------------------------------
89
90SocksiPy
91
92A Python SOCKS module.
93
94(C) 2006 Dan-Haim. All rights reserved.
95
96See LICENSE file for details.
97
98
99*WHAT IS A SOCKS PROXY?*
100
101A SOCKS proxy is a proxy server at the TCP level. In other words, it acts as
102a tunnel, relaying all traffic going through it without modifying it.
103SOCKS proxies can be used to relay traffic using any network protocol that
104uses TCP.
105
106*WHAT IS SOCKSIPY?*
107
108This Python module allows you to create TCP connections through a SOCKS
109proxy without any special effort.
110It also supports relaying UDP packets with a SOCKS5 proxy.
111
112*PROXY COMPATIBILITY*
113
114SocksiPy is compatible with three different types of proxies:
115
1161. SOCKS Version 4 (SOCKS4), including the SOCKS4a extension.
1172. SOCKS Version 5 (SOCKS5).
1183. HTTP Proxies which support tunneling using the CONNECT method.
119
120*SYSTEM REQUIREMENTS*
121
122Being written in Python, SocksiPy can run on any platform that has a Python
123interpreter and TCP/IP support.
124This module has been tested with Python 2.3 and should work with greater versions
125just as well.
126
127
128INSTALLATION
129-------------
130
131Simply copy the file "socks.py" to your Python's `lib/site-packages` directory,
132and you're ready to go. [Editor's note: it is better to use `python setup.py install` for PySocks]
133
134
135USAGE
136------
137
138First load the socks module with the command:
139
140    >>> import socks
141    >>>
142
143The socks module provides a class called `socksocket`, which is the base to all of the module's functionality.
144
145The `socksocket` object has the same initialization parameters as the normal socket
146object to ensure maximal compatibility, however it should be noted that `socksocket` will only function with family being `AF_INET` and
147type being either `SOCK_STREAM` or `SOCK_DGRAM`.
148Generally, it is best to initialize the `socksocket` object with no parameters
149
150    >>> s = socks.socksocket()
151    >>>
152
153The `socksocket` object has an interface which is very similiar to socket's (in fact
154the `socksocket` class is derived from socket) with a few extra methods.
155To select the proxy server you would like to use, use the `set_proxy` method, whose
156syntax is:
157
158    set_proxy(proxy_type, addr[, port[, rdns[, username[, password]]]])
159
160Explanation of the parameters:
161
162`proxy_type` - The type of the proxy server. This can be one of three possible
163choices: `PROXY_TYPE_SOCKS4`, `PROXY_TYPE_SOCKS5` and `PROXY_TYPE_HTTP` for SOCKS4,
164SOCKS5 and HTTP servers respectively. `SOCKS4`, `SOCKS5`, and `HTTP` are all aliases, respectively.
165
166`addr` - The IP address or DNS name of the proxy server.
167
168`port` - The port of the proxy server. Defaults to 1080 for socks and 8080 for http.
169
170`rdns` - This is a boolean flag than modifies the behavior regarding DNS resolving.
171If it is set to True, DNS resolving will be preformed remotely, on the server.
172If it is set to False, DNS resolving will be preformed locally. Please note that
173setting this to True with SOCKS4 servers actually use an extension to the protocol,
174called SOCKS4a, which may not be supported on all servers (SOCKS5 and http servers
175always support DNS). The default is True.
176
177`username` - For SOCKS5 servers, this allows simple username / password authentication
178with the server. For SOCKS4 servers, this parameter will be sent as the userid.
179This parameter is ignored if an HTTP server is being used. If it is not provided,
180authentication will not be used (servers may accept unauthenticated requests).
181
182`password` - This parameter is valid only for SOCKS5 servers and specifies the
183respective password for the username provided.
184
185Example of usage:
186
187    >>> s.set_proxy(socks.SOCKS5, "socks.example.com") # uses default port 1080
188    >>> s.set_proxy(socks.SOCKS4, "socks.test.com", 1081)
189
190After the set_proxy method has been called, simply call the connect method with the
191traditional parameters to establish a connection through the proxy:
192
193    >>> s.connect(("www.sourceforge.net", 80))
194    >>>
195
196Connection will take a bit longer to allow negotiation with the proxy server.
197Please note that calling connect without calling `set_proxy` earlier will connect
198without a proxy (just like a regular socket).
199
200Errors: Any errors in the connection process will trigger exceptions. The exception
201may either be generated by the underlying socket layer or may be custom module
202exceptions, whose details follow:
203
204class `ProxyError` - This is a base exception class. It is not raised directly but
205rather all other exception classes raised by this module are derived from it.
206This allows an easy way to catch all proxy-related errors. It descends from `IOError`.
207
208All `ProxyError` exceptions have an attribute `socket_err`, which will contain either a
209caught `socket.error` exception, or `None` if there wasn't any.
210
211class `GeneralProxyError` - When thrown, it indicates a problem which does not fall
212into another category.
213
214* `Sent invalid data` - This error means that unexpected data has been received from
215the server. The most common reason is that the server specified as the proxy is
216not really a SOCKS4/SOCKS5/HTTP proxy, or maybe the proxy type specified is wrong.
217
218* `Connection closed unexpectedly` - The proxy server unexpectedly closed the connection.
219This may indicate that the proxy server is experiencing network or software problems.
220
221* `Bad proxy type` - This will be raised if the type of the proxy supplied to the
222set_proxy function was not one of `SOCKS4`/`SOCKS5`/`HTTP`.
223
224* `Bad input` - This will be raised if the `connect()` method is called with bad input
225parameters.
226
227class `SOCKS5AuthError` - This indicates that the connection through a SOCKS5 server
228failed due to an authentication problem.
229
230* `Authentication is required` - This will happen if you use a SOCKS5 server which
231requires authentication without providing a username / password at all.
232
233* `All offered authentication methods were rejected` - This will happen if the proxy
234requires a special authentication method which is not supported by this module.
235
236* `Unknown username or invalid password` - Self descriptive.
237
238class `SOCKS5Error` - This will be raised for SOCKS5 errors which are not related to
239authentication.
240The parameter is a tuple containing a code, as given by the server,
241and a description of the
242error. The possible errors, according to the RFC, are:
243
244* `0x01` - General SOCKS server failure - If for any reason the proxy server is unable to
245fulfill your request (internal server error).
246* `0x02` - connection not allowed by ruleset - If the address you're trying to connect to
247is blacklisted on the server or requires authentication.
248* `0x03` - Network unreachable - The target could not be contacted. A router on the network
249had replied with a destination net unreachable error.
250* `0x04` - Host unreachable - The target could not be contacted. A router on the network
251had replied with a destination host unreachable error.
252* `0x05` - Connection refused - The target server has actively refused the connection
253(the requested port is closed).
254* `0x06` - TTL expired - The TTL value of the SYN packet from the proxy to the target server
255has expired. This usually means that there are network problems causing the packet
256to be caught in a router-to-router "ping-pong".
257* `0x07` - Command not supported - For instance if the server does not support UDP.
258* `0x08` - Address type not supported - The client has provided an invalid address type.
259When using this module, this error should not occur.
260
261class `SOCKS4Error` - This will be raised for SOCKS4 errors. The parameter is a tuple
262containing a code and a description of the error, as given by the server. The
263possible error, according to the specification are:
264
265* `0x5B` - Request rejected or failed - Will be raised in the event of an failure for any
266reason other then the two mentioned next.
267* `0x5C` - request rejected because SOCKS server cannot connect to identd on the client -
268The Socks server had tried an ident lookup on your computer and has failed. In this
269case you should run an identd server and/or configure your firewall to allow incoming
270connections to local port 113 from the remote server.
271* `0x5D` - request rejected because the client program and identd report different user-ids -
272The Socks server had performed an ident lookup on your computer and has received a
273different userid than the one you have provided. Change your userid (through the
274username parameter of the set_proxy method) to match and try again.
275
276class `HTTPError` - This will be raised for HTTP errors. The message will contain
277the HTTP status code and provided error message.
278
279After establishing the connection, the object behaves like a standard socket.
280
281Methods like `makefile()` and `settimeout()` should behave just like regular sockets.
282Call the `close()` method to close the connection.
283
284In addition to the `socksocket` class, an additional function worth mentioning is the
285`set_default_proxy` function. The parameters are the same as the `set_proxy` method.
286This function will set default proxy settings for newly created `socksocket` objects,
287in which the proxy settings haven't been changed via the `set_proxy` method.
288This is quite useful if you wish to force 3rd party modules to use a SOCKS proxy,
289by overriding the socket object.
290For example:
291
292    >>> socks.set_default_proxy(socks.SOCKS5, "socks.example.com")
293    >>> socket.socket = socks.socksocket
294    >>> urllib.urlopen("http://www.sourceforge.net/")
295
296
297PROBLEMS
298---------
299
300Please open a GitHub issue at https://github.com/Anorov/PySocks
301