Mike
Mike

Reputation: 80

How to connect to another PC through different networks

When I run both codes on my PC they work. However when I give my friend one of the code to connect with me it doesn't work. Were both on different networks.

I've tried using my Hostname on both. I also tried to use my local IP.

Bottom code I use

import os
import socket


s = socket.socket()
port = 8079


s.bind(("My_Host_Name",port))
print("Scanning income connections")

s.listen(1)
conn, addr = s.accept()


print("Connected to:",addr)


while 1:
    #Sender
    command = input(str("Me: "))
    command = command.encode()
    conn.send(command)
    print("")



    #Reciever 
    data = conn.recv(1024)
    data = data.decode()
    print("Anonymous: "+data)
    print("")

The bottom one is the one I give my friend

import os
import socket


s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

host = "My_Host_Name"
port = 8079



s.connect((host,port))

while 1:
    #Reciever
    data = s.recv(1024)
    data = data.decode()
    print("Anonymous: " + data)
    print("")


    #Sender
    command = input(str("Me: "))
    command = command.encode()
    s.send(command)
    print("")

I expect it to connect through different networks

Upvotes: 1

Views: 216

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 595402

In order for your friend to connect, your server app needs to bind() to a local LAN IP/port of the PC it is running on, and then your client app needs to connect() to the public WAN IP/port of your network router, not the server's LAN IP/port. Your router needs to be configured to port-forward connections from the WAN IP/port to the server's LAN IP/Port. If your router supports uPNP, you can setup that forwarding programmatically in your server code, otherwise you will have to configure it manually in the router's admin interface.

Upvotes: 2

Related Questions