本文实例讲述了python实现超简单端口转发的方法。分享给大家供大家参考。具体如下:
代码非常简单,实现了简单的端口数据转发功能,用于真实环境还需要再修改一下。
代码如下:
#tcp server
import socket
host = ‘127.0.0.1’ #local server ip
host2 = ‘127.0.0.1’ #real server ip
port = 6001 #local server port
port2 = 7001 #real server port
def procdata(data):
return data
#add more code….
print “map server start from ” + host + “:” + str(port) +” to ” + host2 + “:” + str(port2) +”\r\n”
server = socket.socket(socket.af_inet,socket.sock_stream)
server.bind((‘127.0.0.1’,port))
print “127.0.0.1 server start at “+ str(port) +”\r\n”
client = socket.socket( socket.af_inet, socket.sock_stream )
client.connect((host2,port2))
print host +” client connect to ” + host2 + “:”+str(port2)+”\n”
server.listen(5)
ss, addr = server.accept()
print ‘got connected from’,addr
while 1:
msg = ss.recv(20480)
print “get:”+repr(msg)+”\r\n”
client.send(msg)
#print “client send data %s to “%repr(msg)
buf=client.recv(20480)
#print “client recv data %s from “%repr(buf)
ss.send(buf)
print “send:”+repr(buf)+”\r\n”
希望本文所述对大家的python程序设计有所帮助。