Forwarding TCP to another socket

This commit is contained in:
anedroid 2023-03-30 14:18:02 +02:00
parent f97d25a379
commit 5be611e7db
Signed by: anedroid
GPG Key ID: F149EE15E69C7F45
1 changed files with 25 additions and 0 deletions

25
router.py Executable file
View File

@ -0,0 +1,25 @@
#!/usr/bin/python3
import socket, threading, random, sys
dest_addr = sys.argv[1].split(':')
dest_addr = (dest_addr[0], int(dest_addr[1]))
my_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
my_socket.bind(('0.0.0.0', my_port := random.randint(1025, 65535)))
print(f'Listening on 0.0.0.0:{my_port}')
def thread_client(src):
with(src):
dest = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
dest.connect(dest_addr)
threading.Thread(target=router, args=(dest, src)).start()
router(src, dest)
def router(sock1, sock2):
with sock1, sock2:
while True:
data = sock1.recv(1024)
if not data: break
sock2.send(data)
print('Connection closed')
while True:
my_socket.listen()
src, src_addr = my_socket.accept()
print(src_addr)
threading.Thread(target=thread_client, args=(src,), daemon=True).start()