Lev Levitsky
Lev Levitsky

Reputation: 65861

Connecting via hostname using socket works, but not for all ports

I wanted to see how sockets work, so I skimmed through the HOWTO and the docs and tried to write my own code. The server side looks like this:

ssock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
assert socket.gethostname() == HOST
ssock.bind((HOST, PORT))
ssock.listen(5)
while True:
    csock, address = ssock.accept()
    print('Accepted connection from', address)
    t = threading.Thread(target=server, args=(csock,))
    t.start()

The client side is:

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((HOST, PORT))

Those are in one module, so constants are the same. This doesn't work. When I try to connect, I get a ConnectionRefusedError: [Errno 111] Connection refused.

HOWEVER:

  1. When I try to connect via the hostname to another port, it works:

    In [4]: s.connect((HOST, 22))
    
    In [5]: s.recv(1024)
    Out[5]: b'SSH-2.0-OpenSSH_5.9p1 Debian-5ubuntu1\r\n'
    

    (obviously, it's not my app handling the connection on the server).

  2. When I change the host name to the local IP address in the server code, I can connect to my port, too (using IP as the host string).

The combination of these circumstances puzzles me. Can anyone explain this behavior?

EDIT: seems like I can connect with HOST if I use the IP in the server code, too. But why doesn't it work like in the HOWTO?

Upvotes: 1

Views: 6270

Answers (1)

Jean-Paul Calderone
Jean-Paul Calderone

Reputation: 48335

Bind to "" instead of HOST:

ssock.bind(("", PORT))

Upvotes: 5

Related Questions