Connecting to a SOCKS Proxy within Python

The SocksiPy python module provides a simple way to connect via a SOCKS proxy. Within this article we will show you 2 examples on how to use SocksiPy.

General

Below allows you to establish a connection via a SOCKS proxy[1].

import socks
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 8080)
socket.socket = socks.socksocket

import urllib2
print urllib2.urlopen('http://www.google.com').read()

URLLIB2 Only

Should you want to use the SOCKS proxy only with urllib2 then the wrapmodule can be used. This replaces a module’s socket library with a SOCKS socket[2].

import socks
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, '127.0.0.1', 8080)
socks.wrapmodule(urllib2)

import urllib2
print urllib2.urlopen('http://www.google.com').read()

References

[1] http://nullege.com/codes/search/socks.wrapmodule
[2] http://socksipy.sourceforge.net/

Rick Donato

Want to become a programming expert?

Here is our hand-picked selection of the best courses you can find online:
Python Zero to Hero course
Python Pro Bootcamp
Bash Scripting and Shell Programming course
Automate with Shell Scripting course
The Complete Web Development Bootcamp course
and our recommended certification practice exams:
AlphaPrep Practice Tests - Free Trial