Python port forwarding/multiplexing server

做~自己de王妃 提交于 2019-12-03 03:16:35

I am not comfortable with twisted or scapy, but it's quite straightforward to do this with vanilla python sockets. An extra advantage of that is that it will be even more portable. This code works in my limited tests:

#!/usr/bin/python
from socket import *
bufsize = 1024 # Modify to suit your needs
targetHost = "somehost.yourdomain.com"
listenPort = 1123

def forward(data, port):
    print "Forwarding: '%s' from port %s" % (data, port)
    sock = socket(AF_INET, SOCK_DGRAM)
    sock.bind(("localhost", port)) # Bind to the port data came in on
    sock.sendto(data, (targetHost, listenPort))

def listen(host, port):
    listenSocket = socket(AF_INET, SOCK_DGRAM)
    listenSocket.bind((host, port))
    while True:
        data, addr = listenSocket.recvfrom(bufsize)
        forward(data, addr[1]) # data and port

listen("localhost", listenPort)

A different but sort of related solution to forwarding ports, not multiplexing (not answering the specific question but hopefully matching related ones - this is what I was looking for at least):

http://www.linux-support.com/cms/forward-network-connections-with-python/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!