I am trying to create a peer-to-peer python app using the socket library. I am curious to know if there is any way in which I can use the socket library to connect to another computer outside my local network without any manual steps like opening ports on the router for port forwarding. Do I need to use an already open port on the router (given that routers have some ports open on default)? Please guide me. I am new to socket and networking.
My code till now:-
client-1 (sender)
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((MYPUBLICIP, 433))
s.send(b"HELLO!")
s.close()
client 2 (receiver)
import socket
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((MYPRIVATEIP, 433))
s.listen()
conn, addr = s.accept()
with conn:
print(f"[CONNECTION_ALERT] Received connection request from {addr}.")
while True:
data = conn.recv(1026).decode('utf-8')
if not data:
break
print(data)
The error I am getting:
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it
If needed, my python version is 10
CodePudding user response:
Solution to connect two hosts on the same local network
Error message suggest that your firewall probably blocked the network traffic, you can try to disable your firewall and try again, but it is not advisable. If you want to play with network stuff i would suggest you create a local lab that is not connected to internet, like VM's or old laptops/pc.
Solution to connect two hosts NOT on the same local network
If you want to connect two hosts that are not on the same local network then the problem becomes more complicated, and have several possible solutions:
- Ask your ISP for public IP (easy but usually comes with extra costs)
- Use available software solutions to create private networks over the internet, like hamachi or ngrok (also easy but depending on the usecase cost will vary)
- Exploiting naive NAT's by using STUN (hard to implement but satisfying if done right, nice explanation of how it was implemented in OpenTTD multiplayer)