Ray
Ray

Reputation: 321

How to connect with Python Sockets to another computer on the same network

So I was trying to figure out a way to use sockets to make a terminal-based chat application, and I managed to do it quite well. Because I could only test it on one computer, I didn't realize that it might not work on different computers. My code is as simple as this:

# Server
import socket
HOST = "0.0.0.0"
PORT = 5555

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((HOST, PORT))
    s.listen()
    while True:
        conn, addr = s.accept()
        with conn:
            print("Connected to", addr)
            data = conn.recv(1024)
            print("Received:", data.decode())
            conn.sendall(data)
# Client
import socket
HOST = "192.168.0.14"
PORT = 5555

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.connect((HOST, PORT))
    s.sendall(b"Hello this is a connection")
    data = s.recv(1024)
print("Received:", data.decode())

I've tried changing the ip to 0.0.0.0, use gethostname a lot of other things, but it just doesn't work. The server is up and running, but the client can't connect. Can someone help me?

Upvotes: 1

Views: 2872

Answers (1)

shrewmouse
shrewmouse

Reputation: 6020

I believe that 0.0.0.0 means connect from anywhere which means that you have to allow port 5555 through your firewall.

enter image description here

Instead of 0.0.0.0 use localhost as the address in both the client and the server.

I just tested your code using localhost for the server and the client and your program worked.

server:

Connected to ('127.0.0.1', 53850)
Received: Hello this is a connection

client:

Received: Hello this is a connection

As you can see, all that I changed was the address on both the server and the client. If this doesn't work then there is something outside of your program that is preventing you from success. It could be a permissions issue or another program is listening on port 5555.

server.py

# Server
import socket
HOST = "0.0.0.0"
HOST = "localhost"
PORT = 5555

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((HOST, PORT))
    s.listen()
    while True:
        conn, addr = s.accept()
        with conn:
            print("Connected to", addr)
            data = conn.recv(1024)
            print("Received:", data.decode())
            conn.sendall(data)

if __name__ == '__main__':
    pass

client.py

# Client
import socket
HOST = "localhost"
PORT = 5555

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.connect((HOST, PORT))
    s.sendall(b"Hello this is a connection")
    data = s.recv(1024)
print("Received:", data.decode())

if __name__ == '__main__':
    pass

Upvotes: 1

Related Questions