Skip to content

Instantly share code, notes, and snippets.

@bosmacs
Last active June 1, 2020 09:29
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bosmacs/538747 to your computer and use it in GitHub Desktop.
Save bosmacs/538747 to your computer and use it in GitHub Desktop.
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()
@rthill
Copy link

rthill commented Dec 11, 2018

Thanks, you save me some time to create a similar tool.

@tsundokul
Copy link

Useful, indeed!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment