-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathp2p_connection.py
More file actions
49 lines (36 loc) · 1.54 KB
/
p2p_connection.py
File metadata and controls
49 lines (36 loc) · 1.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# p2p_connection.py
import socket
import threading
from stun_discovery import discover_public_ip_port
ext_ip, ext_port, nat_type = discover_public_ip_port()
print(f"My IP: {ext_ip}, My port: {ext_port}, NAT Type: {nat_type}")
# Ask for the peer's IP and port
peer_ip = input("Enter the peer's IP address: ")
peer_port = int(input("Enter the peer's port: "))
talking_port = 42424
def receive_messages():
print(f"Start listening..")
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # Enable address reuse
sock.bind(('0.0.0.0', peer_port))
while True:
data, addr = sock.recvfrom(1024)
print(f"\nPeer {addr}: {data.decode()}\n")
print("Enter message to send: ", end=">")
def main():
# Start the receiving thread
recv_thread = threading.Thread(target=receive_messages, daemon=True)
recv_thread.start()
print('Start punching hole..')
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # Enable address reuse
sock.bind(('0.0.0.0', peer_port))
sock.sendto(b'0', (peer_ip, talking_port))
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # Enable address reuse
sock.bind(('0.0.0.0', talking_port))
while True:
message = input("\nEnter message to send: ")
sock.sendto(message.encode(), (peer_ip, peer_port))
if __name__ == "__main__":
main()