python receiving data from a friend

Viewed 61

I'm new to this whole shazam and I'm a little confused. I want to have a server receive data on my computer, and a friend send data on his own computer. The code for my server is as follows:

import socket

HOST = 'HOST' 
PORT = PORT    

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((HOST, PORT))
    s.listen()
    conn, addr = s.accept()
    with conn:
        print('Connected by', addr)
        while True:
            data = conn.recv(1024)
            if not data:
                break
            conn.sendall(data)

I've blanked out the host ip and the port but I'm not really sure which one I'm supposed to be using for either tbh. The client code goes as follows

import socket

HOST = 'HOST' 
PORT = PORT   

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.connect((HOST, PORT))
    s.sendall(b'Hello, world')
    data = s.recv(1024)

print('Received', repr(data))

So my server receives it only when I run the client, not my friend. My question is what IP and ports am i supposed to use? Where can i find these numbers? Why does it only work when I run the client and how can I fix this? And if anybody can direct me to some resources about this topic I don't know what to search up :( Thanks in advance!

1 Answers

The server should bind to the IP address of whatever interface it expects to receive traffic on. If it might receive traffic on multiple interfaces, you could bind to 0.0.0.0, which means 'all interfaces'. Whatever IP you decide on is what you should set for the server HOST value. For the server port, it could be a specific port or any port (port 0). Just be aware that the client will need to know which port the server is listening on.

The client should connect to the IP address or hostname and port of your server whose address is publicly accessible. This really depends on the network setup.

I suggest having your client connect to the same network as your server and trying again. If it doesn't work, make sure you're server is listening on 0.0.0.0.

If you are on different networks, these networks need to be bridged in some way.

Related