唯一目的:短平快
语言:python
模块:sys,socket,threading
服务器IP:192.168.1.6
中间机器:192.168.138.128
客户端IP:192.168.1.6
服务器和客户端都是真实物理机,中间机器是VMware虚拟机。用三个不同机器效果也一样。
#coding=utf-8
import sys
import threading
import socket
def main():
if len(sys.argv[1:])!=5:
print "Example: python tcp_proxy 127.0.0.1 9999 10.12.131.1 90000 True"
sys.exit(0)
local_host=sys.argv[1]
local_port=int(sys.argv[2])
remote_host=sys.argv[3]
remote_port=int(sys.argv[4])
receive_first=sys.argv[5]
if "True" in receive_first:
receive_first=True
else:
receive_first=False
server_loop(local_host,local_port,remote_host,remote_port,receive_first)
def server_loop(local_host,local_port,remote_host,remote_port,receive_first):
server=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
try:
server.bind((local_host,local_port))
except:
print "failed!!,check the sockets or correct permisssion!"
sys.exit(0)
print "listening on %s,%d" % (local_host,local_port)
server.listen(5)
while True:
client_socekt,addr=server.accept()
print "received incoming connection from %s,%d"% (addr[0],addr[1])
proxy_thread=threading.Thread(target=proxy_handler,args=(client_socekt,remote_host,remote_port,receive_first))
proxy_thread.start()
def proxy_handler(client_socket,remote_host,remote_port,receive_first):
#下面两句连接服务器,获得socket对象!
remote_socket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
remote_socket.connect((remote_host,remote_port))
while True:
#如果接受到来自客户的数据,就转发到服务器
local_buffer=receive_from(client_socket)
if len(local_buffer):
print "received %d bytes from localhost" % len(local_buffer)
remote_socket.send(local_buffer)
print "send to remote >>>"
#如果接受到来自服务器的数据,就转发到客户端
remote_buffer=receive_from(remote_socket)
if len(remote_buffer):
print "received %d bytes from remote ." % (len(remote_buffer))
client_socket.send(remote_buffer)
print "send to localhost <<<"
#如果双方都没数据发过来,哈哈,那我就关闭,睡觉喽。
if not len(local_buffer) or not len(remote_buffer):
client_socket.close()
remote_socket.close()
print "no more information, closing connnection !!"
break
#接收发送端发送的所有消息
def receive_from(connection):
buffer=""
connection.settimeout(2)
try:
while True:
data=connection.recv(4096)
if not data:
break
buffer+=data
except:
pass
return buffer
main()
代理可用来突破分段网络: