Twisted Matrix

How to write port-forwarding program using Twisted

Recently I was faced with an issue where a long running process is listening on loop back IP ( on port 8080 on one of our servers and client programs on other machines are trying to access it on server’s local IP  We ended up at this situation when we have updated server configuration and restarted the server program and forgot to change IP binding info in config file from loop back to local IP. Server got busy with it’s work, with lots of customer’s connections already, by the time we have discovered that some services of  server are not accessible to client programs on other machines. So, the dummy’s guide to fixing it by changing config and restarting the server program is not an option as we can’t risk to disconnect existing customers. So, hot patching is the only option until we can restart the program at next scheduled down time.

I could have fixed this in couple of ways either by adding few lines to iptables configuration or by writing simple socket program in python. The task is to forward data coming in on local IP port 8080 to loop back IP ( port 8080 and send replies back to source address. Forwarding one socket data to other socket is pretty trivial using Python’s socket library and Twisted made it even more trivial, so I went with the following solution using Twisted.

__author__ = 'godson'

from twisted.protocols.portforward import ProxyFactory
from twisted.application import internet,service

src_ip = ""
src_port = 8080
dst_ip = ""
dst_port = 8080

application = service.Application("Proxy")
server = ProxyFactory(dst_ip, dst_port)
ps = internet.TCPServer(src_port,server,50,src_ip)


That’s it. Now, all I needed to do is to run this program by the following command

twistd -y

This simple program is made possible by the heavy lifting done by twisted library. Interested folks can look under hood at twisted’s module.

Leave a Reply

Your email address will not be published. Required fields are marked *