Last active
June 1, 2020 09:29
-
-
Save bosmacs/538747 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
Useful, indeed!