2

I am constructing a TCP reverse proxy. I can successfully send and receive data. However, I would like to change the outgoing port. So for example, I accept connections on say 8000, then proxy that data to another host on 8001. Sometime down the road, I would like to change that port to 8002 as fast as possible. I want to be able to do this by having the proxy run in one thread, and the rest of the work in another. So to change the port all I would really have to do is call something like:

changePort(8002) # Or whatever number I so choose

I have dug around the internet and came across an example using twisted:

from twisted.internet import reactor
from twisted.protocols import portforward

def server_dataReceived(self, data):
    print 'Server received data:', data
    portforward.Proxy.dataReceived(self, data)
portforward.ProxyServer.dataReceived = server_dataReceived

def client_dataReceived(self, data):
    print 'Client received data:', data
    portforward.Proxy.dataReceived(self, data)
portforward.ProxyClient.dataReceived = client_dataReceived

reactor.listenTCP(8000, portforward.ProxyFactory('someIP', 8001))
reactor.run()

This works great, however when I try to use Python threading, even though I started everything in a new thread, code executed in the main thread hangs until I stop the program (Ctrl+c) where it quickly ran and exited.

Lastly, I also came across this Python Proxy in Less Than 100 Lines of Code which also works well, and may have a better way to change the outgoing port.

Thanks for the help!

KosherBacon
  • 172
  • 1
  • 11

0 Answers0