实现端口的转发
tcpsocket.py 对基础的socket进行了封装
import socketclass baseSocket:def service(host:str,port:int,maxSuspend:int)->socket: service_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) # 创建 socket 对象service_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # 允许socket地址复用,防止出现 address alread use 问题service_socket.bind((host,port))service_socket.listen(maxSuspend)return service_socketdef client(host:str,port:int):client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)client.connect((host, port))return client
portForward.py 端口转发的程序
# coding: gbk python文件的编码格式
import tcpSocket
import socket
import threadingdef forward(localSocket, localAddr ,remoteSocket,remoteAddr):while True:localdata = localSocket.recv(1024)if not localdata:exit(0)remoteSocket.send(localdata)def connectTask(localSocket, localAddr ,remoteSocket,remoteAddr):thdlocal = threading.Thread(target=forward, args=(localSocket,localAddr,remoteSocket,remoteAddr))thdlocal.daemon=True #设置daemon=True会标记其为守护线程,如果剩下的线程只有守护线程时,整个python程序都会退出thdremote = threading.Thread(target=forward, args=(remoteSocket,remoteAddr,localSocket,localAddr))thdremote.daemon=True #设置daemon=True会标记其为守护线程,如果剩下的线程只有守护线程时,整个python程序都会退出thdlocal.start()thdremote.start()if __name__ == "__main__":host = socket.gethostname()localPort = 8090remotePort = 8081maxlisten = 5localservice = tcpSocket.baseSocket.service(host,localPort,maxlisten)remoteservice = tcpSocket.baseSocket.service(host,remotePort,maxlisten)while True:localSocket,localAddr = localservice.accept()print(f"连接地址为{localAddr}")remoteSocket,remoteAddr = remoteservice.accept()print(f"连接地址为{remoteAddr}")thd = threading.Thread(target=connectTask, args=(localSocket,localAddr,remoteSocket,remoteAddr))thd.daemon=True #设置daemon=True会标记其为守护线程,如果剩下的线程只有守护线程时,整个python程序都会退出thd.start()