Created
December 8, 2023 02:23
-
-
Save aaronjamt/2a96df697c1dac4546eb148b143d5216 to your computer and use it in GitHub Desktop.
[Python] Forward all packets between open TCP sockets
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import socket, threading, select | |
def _forwardBetween(*sockets, endOnAnySocketClose=True, daemonize=True): | |
def _handler(sockets): | |
sockets = list(sockets) | |
print(sockets) | |
# Set all sockets to nonblocking so we don't have to wait for them | |
[socket.setblocking(False) for socket in sockets] | |
while True: | |
socks = select.select(sockets, [], sockets)[0] | |
# Iterate over all sockets with new activity | |
for in_sock in select.select(sockets, [], sockets)[0]: | |
got = in_sock.recv(1024) | |
if len(got) < 1: | |
# Socket closed, remove it from the list of sockets | |
print("Socket closed.") | |
sockets.remove(in_sock) | |
if endOnAnySocketClose: | |
# Close all other sockets and exit | |
print("Closing all other connected sockets") | |
[socket.close() for socket in sockets] | |
return | |
print(f"Got {len(got)} bytes from socket") | |
# Forward the data to all other connected sockets | |
for out_sock in [sock for sock in sockets if sock is not in_sock]: | |
out_sock.send(got) | |
if daemonize: | |
# Start actual function in a new thread | |
threading.Thread(target=_handler,daemon=True,args=(sockets,)).start() | |
else: | |
# Start actual function in the current thread | |
_handler(sockets) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment