About Me

My name is Ricardo Pascal, I'm a developer and sysadmin who lives in Florianopolis/Brazil. I enjoy work with projects related to Linux, Python, Science, Web, Django and Network.

g+ A kickstarter for the next version of Django Rest Framework. | A empresa Neoprospecta está contratando 2 desenvolvedores python para trabalhar em projetos de bioinformática... | A empresa Neoway está contratando desenvolvedor Python para trabalhar num projeto web com Django em ... | I wrote a small article showing how to display a form, and create objects from them using views in five... | | A Pixeon está com várias vagas abertas. (Inclusive programador Python). | "When deciding which server architecture to use for your environment, there are many factors to consider... | | Segue uma proposta de lei feita pelo DEPUTADO Missionário José Olimpio. É uma lei que visa nos proteger... | By +Ruben Bolling    http://gocomics.typepad.com/tomthedancingbugblog/ THU MAY 29, 2014 AT 06:50 AM ... | Let's send also some cancer, radioactive material, ebola, Justin Bieber and Brazilian Funk  ¬¬ | "The most extreme case is David Whitlock, the M.I.T.-trained chemical engineer who invented AO+. He ... | If I had 8k euros to spare, I would definitely buy one :) | | Esse link eu salvei nos favoritos. Vale a pena! | Estamos procurando Jedi Back-end Engineer We are looking for a engaged and dedicated software engineer... | django-auth-imap is a package that let you use a IMAP server as backend for authentication in your django... | Would be half-cannibalism if a man made of pig organs eat some bacon? Jokes apart, that's a big news... | "The fact that so many homeless men suffered a TBI before losing their home suggests such injuries could... | I finally found a place with plenty of space to fly my f330, now I just have to lose the fear of flying... |

A python proxy in less than 100 lines of code

What is a tcp proxy?

It's a intermediary server intended to act in name of a client, and sometimes to do something useful with the data before it reaches the original target. Let's see a picture:


My idea was to produce a proxy using only the default python library, and to guide me during development I set the following:

  • Each new client connection to our proxy must generate a new connection to the original target.
  • Each data packet that reaches our proxy must be forwarded to the original target.
  • Each data packet received from the target must be sent back to the correct client
  • The proxy must accept multiple clients
  • Must be fast
  • Must have a low resource usage

The result:

# This is a simple port-forward / proxy, written using only the default python
# library. If you want to make a suggestion or fix something you can contact-me
# at voorloop_at_gmail.com
# Distributed over IDC(I Don't Care) license
import socket
import select
import time
import sys

# Changing the buffer_size and delay, you can improve the speed and bandwidth.
# But when buffer get to high or delay go too down, you can broke things
buffer_size = 4096
delay = 0.0001
forward_to = ('smtp.zaz.ufsk.br', 25)

class Forward:
    def __init__(self):
        self.forward = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    def start(self, host, port):
            self.forward.connect((host, port))
            return self.forward
        except Exception, e:
            print e
            return False

class TheServer:
    input_list = []
    channel = {}

    def __init__(self, host, port):
        self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.server.bind((host, port))

    def main_loop(self):
        while 1:
            ss = select.select
            inputready, outputready, exceptready = ss(self.input_list, [], [])
            for self.s in inputready:
                if self.s == self.server:

                self.data = self.s.recv(buffer_size)
                if len(self.data) == 0:

    def on_accept(self):
        forward = Forward().start(forward_to[0], forward_to[1])
        clientsock, clientaddr = self.server.accept()
        if forward:
            print clientaddr, "has connected"
            self.channel[clientsock] = forward
            self.channel[forward] = clientsock
            print "Can't establish connection with remote server.",
            print "Closing connection with client side", clientaddr

    def on_close(self):
        print self.s.getpeername(), "has disconnected"
        #remove objects from input_list
        out = self.channel[self.s]
        # close the connection with client
        self.channel[out].close()  # equivalent to do self.s.close()
        # close the connection with remote server
        # delete both objects from channel dict
        del self.channel[out]
        del self.channel[self.s]

    def on_recv(self):
        data = self.data
        # here we can parse and/or modify the data before send forward
        print data

if __name__ == '__main__':
        server = TheServer('', 9090)
        except KeyboardInterrupt:
            print "Ctrl C - Stopping server"

The explanation

class Forward()

The Forward class is the one responsible for establishing a connection between the proxy and the remote server(original target).

class TheServer().main_loop()

The input_list stores all the avaiable sockets that will be managed by select.select, the first one to be appended is the server socket itself, each new connection to this socket will trigger the on_accept() method.

If the current socket inputready (returned by select) is not a new connection, it will be considered as incoming data(maybe from server, maybe from client), if the data lenght is 0 it's a close request, otherwise the packet should be forwarded to the correct endpoint.

class TheServer().on_accept()

This method creates a new connection with the original target (proxy -> remote server), and accepts the current client connection (client->proxy). Both sockets are stored in input_list, to be then handled by main_loop. A "channel" dictionary is used to associate the endpoints(client<=>server).

class TheServer().recv()

This method is used to process and forward the data to the original destination ( client <- proxy -> server ).

class TheServer().on_close()

Disables and removes the socket connection between the proxy and the original server and the one between the client and the proxy itself.

That's it.

by Ricardo Pascal on Aug 29, 2012

comments powered by Disqus