2

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!

terrabyte
  • 307
  • 1
  • 3
  • 12
  • Check out this link, it may solve your issue on which ports to use. http://www.steves-internet-guide.com/tcpip-ports-sockets/ – noahjillson Mar 13 '20 at 05:22
  • the easiest way is probably to use ngrok which sets up a tunnel... (google it) ... another would be to setup port forwarding on your router and to check your ip address (whatismyip.org) and have your friend connect directly to your router, which will forward to your socket (assuming you setup port forwarding correctly on your router) – Joran Beasley Mar 13 '20 at 05:27
  • What code does your friend use? – cup Mar 13 '20 at 05:39
  • @cup same as the client code i posted – terrabyte Mar 13 '20 at 05:41

1 Answers1

1

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.

vincent
  • 1,370
  • 2
  • 13
  • 29