python端口转发_Python端口转发/多路复用服务器

I would like to make server that listen on UDP port 162 (SNMP trap) and then forwards this traffic to multiple clients. Also important is that the source port & address stays same (address spoofing).

I guess that best tool for this would be Twisted or Scapy or maybe vanilla sockets,

only I can't find anything in the documentation for Twisted about source address spoofing/forging.

Any solution for this?

Edit:added bounty, mybe any solution with iptables?

解决方案

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值