python 写一个端口转发的代码
时间: 2024-01-14 19:02:38 浏览: 149
基于Python实现的端口自动转发工具源码,带图形界面
以下是一个简单的 Python 端口转发代码示例:
```python
import socket
def forward(source, dest):
while True:
data = source.recv(1024)
if not data:
break
dest.sendall(data)
def main():
local_host = '127.0.0.1'
local_port = 8080
remote_host = 'example.com'
remote_port = 80
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as local_sock:
local_sock.bind((local_host, local_port))
local_sock.listen(1)
print(f'Listening on {local_host}:{local_port}')
while True:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as remote_sock:
remote_sock.connect((remote_host, remote_port))
source, addr = local_sock.accept()
print(f'Accepted connection from {addr[0]}:{addr[1]}')
forward_thread = threading.Thread(target=forward, args=(source, remote_sock))
forward_thread.start()
if __name__ == '__main__':
main()
```
此代码将本地主机的 8080 端口的所有流量转发到远程主机的 80 端口。使用 `socket` 模块创建两个套接字,一个监听本地端口,另一个连接远程主机。然后,它在两个套接字之间建立一个转发线程,将所有来自本地套接字的数据发送到远程套接字。
阅读全文