Skip to content

Instantly share code, notes, and snippets.

@darkf
Created April 11, 2013 05:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save darkf/5360981 to your computer and use it in GitHub Desktop.
Save darkf/5360981 to your computer and use it in GitHub Desktop.
Twisted TCP/IP Proxy
# Twisted TCP/IP proxy
# You would set REAL_IP to the IP of the server you want to proxy
# then override the domain name in your hosts file. Run this,
# and then it should proxy through.
# I don't think this works with more than one concurrent client, and in that case you should refactor this code a bit. (Sorry.)
# Copyright (c) 2013 darkf; licensed under CC-0 (or in the public domain if applicable)
from twisted.internet.protocol import Factory, ClientFactory, Protocol
from twisted.protocols.basic import LineReceiver
from twisted.internet import reactor, defer
REAL_IP = "ip here"
class MyProxyClient(Protocol):
def __init__(self, server):
self.server = server
def connectionMade(self):
print "connection to server made"
self.server.dataQueue.get().addCallback(self.writeClientData)
def connectionLost(self, reason):
print "conn to server lost (%s)" % reason
def dataReceived(self, data):
self.server.writeServerData(data)
def writeClientData(self, data):
print "writing client data:", data
self.transport.write(data)
self.server.dataQueue.get().addCallback(self.writeClientData)
class MyProxyClientFactory(ClientFactory):
def __init__(self, server):
self.proto = None
self.server = server
def buildProtocol(self, addr):
self.proto = MyProxyClient(self.server)
return self.proto
class MyProxyServer(Protocol):
def __init__(self):
self.clientFactory = MyProxyClientFactory(self)
def connectionMade(self):
print "got connection from client"
reactor.connectTCP(REAL_IP, 8080, self.clientFactory)
self.dataQueue = defer.DeferredQueue()
def connectionLost(self, reason):
print "conn to us lost (%s)" % reason
if self.clientFactory.proto:
print "disconnecting from server too"
self.clientFactory.proto.transport.loseConnection()
def dataReceived(self, data):
self.dataQueue.put(data)
def writeServerData(self, data):
self.transport.write(data)
class MyProxyServerFactory(Factory):
def buildProtocol(self, addr):
return MyProxyServer()
reactor.listenTCP(8080, MyProxyServerFactory())
reactor.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment