A
A
AlexGenesis2021-08-03 18:49:22
Python
AlexGenesis, 2021-08-03 18:49:22

How to pierce UDP correctly?

Good day, the other day I became interested in TCP \ UDP penetration and decided to write a small program, my task was to first connect 2 clients to the main server, and after that they would already establish a direct connection between themselves, but as you might guess, I did not get a satisfactory result, so I will be grateful for any answers.

Server:

import socket, threading, time

server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_socket.bind(("192.168.0.122", 4545))

addres_lt = []

def accept():
    while True:
        message, addres = server_socket.recvfrom(1024)
        addres_lt.append(addres)
        port = str(addres[1])
        server_socket.sendto(port.encode(), addres)
        
def main():
    while True:
        if len(addres_lt) == 2:
            print(addres_lt)
            send_port()
            time.sleep(0.5)

def send_port():
    for sock in addres_lt:
        if sock == addres_lt[0]:
            server_socket.sendto(str(addres_lt[1][1]).encode(), sock)
        else:
            server_socket.sendto(str(addres_lt[0][1]).encode(), sock)

p1 = threading.Thread(target=accept)
p2 = threading.Thread(target=main)
p1.start()
p2.start()


Customer:
import socket, time, threading

client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
client_socket.settimeout(1.0)
message = 'test'
addr = ("47.23.232.259", 4545)
get_sock = False

client_socket.sendto(message.encode(), addr)

data, server = client_socket.recvfrom(1024)

data = data.decode()

while get_sock == False:
    try:
        adr, server = client_socket.recvfrom(1024)
        get_sock = True
    except:
        pass

server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_socket.bind(("192.168.0.122", int(data)))

adr = ("47.23.232.259", int(adr.decode()))

def recv():
    while True:
        message, addres = server_socket.recvfrom(1024)
        print(message)

def send():
    while True:
        print("My port: ", data,"\nTry connect to: ", adr)
        server_socket.sendto("Connection established".encode(), adr)

p1 = threading.Thread(target=recv)
p2 = threading.Thread(target=send)
p1.start()
p2.start()


I apologize in advance for the illiterate code, I wrote in a hurry.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question