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?

1 Answer

Bind to "" instead of HOST:

ssock.bind(("", PORT)) 
4

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like