How to make a simple proxy server in python?

I wanted to make a very simple proxy using python (mainly to understand how it works). I'm talking about a generic TCP proxy, not just http. I built the following code, however, it seems to work in only one way: i.e. The request is sent, but I never get a response. Here is the code:

import socket import argparse #Args parser = argparse.ArgumentParser(description='ProxyDescription') parser.add_argument('-l', '--listen', action='store', help='Listening port', default=80, type=int) parser.add_argument('destination', action='store', help='Destination host') parser.add_argument('port', action='store', help='Destination port', type=int) args = parser.parse_args() #Server s1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s1.bind(('', args.listen)) s1.listen(1) conn1, addr1 = s1.accept() #Client s2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s2.connect((args.destination, args.port)) s2.setblocking(0) print "Connected by ", addr1 while 1: datato = conn1.recv(1024) if not datato: print "breaking to" break s2.send(datato) print "data send : " + datato try: datafrom = s2.recv(1024) print "reveived data : " + datafrom if not datafrom: print "breakinf from" break print "datafrom: " + datafrom conn1.send(datafrom) except socket.error, msg: print "error rcving: " + str(socket.error) + " || " + str(msg) continue print "the end ... closing" conn1.close() s2.close() 

My test just runs this script and telnet through it. If I look with wirehark, I see that the request is completely understood by the server, and I get a response, however, I never get a response in telnet. (testing with a simple GET / on google) I feel that the problem is with a "blocking" / "non-blocking" socket, but I cannot figure out where it is.

+7
source share
2 answers

I wrote a short article about creating a proxy server in python, it works asynchronously and can handle a large number of connections. Here is the link: http://voorloopnul.com/blog/a-python-proxy-in-less-than-100-lines-of-code/ (it uses only the default libraries.)

+8
source

Perhaps this recipe will help you http://code.activestate.com/recipes/114642/

+4
source

All Articles