Testing the Status of a SOCKS5 Proxy in Python

September 11 2012 · tech python

I’ve been working on a proxy testing application in Clojure and have been thinking about porting it to Python. There are a couple of Python libraries that I could use to test the status of a SOCKS proxy. PyCurl is a Python wrapper of the C library curl, this makes it easy to do HTTP requests by using a SOCKS proxy. Another option is socksipy which essentially provides a wrapper around an instance of the socket module. Both of these establish a full connection with the proxy.

Looking at the SOCKS5 protocol we can see that it’s possible to test the status of a SOCKS5 proxy just by reading the response to the initial greeting packet. Both PyCurl and socksipy establish a full SOCKS connection with the server. This full connection is necessary if we want to send data through the proxy, but because we only need to check the status of the proxy, we can write a script to send just the first packet and read the response.

The format of the greeting packet is as follows (source):

And the server responds:

Using Python we can write a small script to test this:

import socket
import struct

sen = struct.pack('BBB', 0x05, 0x01, 0x00)

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('localhost', 9050))

data = s.recv(2)

version, auth = struct.unpack('BB', data)

If version is 5 and auth is 0 (no authentication), then the proxy is up and available for us to connect to.