Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
from twisted.internet.protocol import DatagramProtocol
from twisted.internet import reactor
forwardMap = {
5500 : [ "192.168.110.32:5500", "10.0.1.1:5500" ],
5499 : [ "192.168.110.32:5499" ],
15501 : [ "localhost:5501" ]
}
class Forward(DatagramProtocol):
def __init__(self, targetTuples):
self._targetTuples = targetTuples
def datagramReceived(self, data, hostAndPort):
for targetHost, targetPort in self._targetTuples:
#print "forwarding %r from %s:%d to %s:%d" % (data, host, port, targetHost, targetPort)
self.transport.write(data, (targetHost, targetPort))
def bindListeners(resolvedMap):
for port, targetPairs in resolvedMap.items():
reactor.listenUDP(port, Forward(targetPairs))
def resolved(ip, lport, host, dport, rmap={}):
rmap.setdefault(lport, []).append((ip, dport))
cons = lambda a, b: a + b
if (len(reduce(cons, forwardMap.values())) == len(reduce(cons, rmap.values()))):
bindListeners(rmap)
for port, destinations in forwardMap.items():
strPairs = [d.split(':') for d in destinations]
map(lambda hostAndPort: (reactor.resolve(hostAndPort[0]).addCallback(resolved, port, hostAndPort[0], int(hostAndPort[1]))), strPairs)
reactor.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment