使用套接字通过主机名连接有效,但不适用于所有端口

Lev*_*sky 1 python sockets networking

我想看看套接字是如何工作的,所以我浏览了HOWTO文档,并尝试编写自己的代码。服务器端看起来像这样:

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()
Run Code Online (Sandbox Code Playgroud)

客户端是:

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((HOST, PORT))
Run Code Online (Sandbox Code Playgroud)

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'
    
    Run Code Online (Sandbox Code Playgroud)

    (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?

Jea*_*one 5

绑定到 "" 而不是 HOST:

ssock.bind(("", PORT))
Run Code Online (Sandbox Code Playgroud)