Created
April 15, 2023 22:31
-
-
Save fyx99/10fb8196dc41fb90dcb23d7ee722babc to your computer and use it in GitHub Desktop.
TCP Rerouting using Pythons socket module
This file contains 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 multiprocessing | |
import time | |
import socket | |
def process_1(): | |
# this demonstrates a third party lib | |
print("Process 1 is running") | |
while True: | |
time.sleep(10) | |
host = "localhost" | |
port = 5555 | |
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
client.connect((host,port)) | |
client.send(b"9") | |
response = client.recv(4096) | |
print("Client", response) | |
client.close() | |
def process_2(): | |
# this demonstrates the functionality of the internal port forwarder | |
print("Process 2 is running") | |
# Define the local and remote addresses | |
LOCAL_HOST = 'localhost' | |
LOCAL_PORT = 5555 | |
REMOTE_HOST = 'localhost' | |
REMOTE_PORT = 4444 | |
# Create a socket object | |
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
# Bind the socket to a local address | |
server_socket.bind((LOCAL_HOST, LOCAL_PORT)) | |
# Listen for incoming connections | |
server_socket.listen(1) | |
print('Server listening on {}:{}'.format(LOCAL_HOST, LOCAL_PORT)) | |
# Accept incoming connections and forward traffic to the remote host | |
while True: | |
client_socket, client_address = server_socket.accept() | |
print('Accepted connection from {}:{}'.format(client_address[0], client_address[1])) | |
# Connect to the remote host | |
remote_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
remote_socket.connect((REMOTE_HOST, REMOTE_PORT)) | |
# Forward incoming data to the remote host | |
data = client_socket.recv(1024) | |
print("client sent", data) | |
if not data: | |
break | |
remote_socket.sendall(data) | |
# Forward outgoing data from the remote host back to the client | |
data = remote_socket.recv(1024) | |
print("remote sent", data) | |
if not data: | |
break | |
client_socket.sendall(data) | |
# Close the sockets | |
client_socket.close() | |
remote_socket.close() | |
if __name__ == '__main__': | |
p1 = multiprocessing.Process(target=process_1) | |
p2 = multiprocessing.Process(target=process_2) | |
p1.start() | |
p2.start() | |
p1.join() | |
p2.join() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment