我希望能够执行以下简单的服务器代码:
import socket
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 22331 # Reserve a port
s.bind((host, port)) # Bind to the port
s.listen(5) # Now wait for client connection.
while True:
c, addr = s.accept() # Establish connection with client.
print('Got connection from', addr)
c.send('Thank you for connecting')
c.close()
执行时出现以下错误:
OSError: [Errno 99] Cannot assign requested address
为什么操作系统无法将指定的端口与地址绑定?
host = '0.0.0.0'
。socket.gethostname()
返回的是主机名,而不是 IP 地址。 - Valentin Lorentz0.0.0.0
。看起来你的gethostname()
返回了一个IP地址/名称,但它并没有解析到你正在执行脚本的主机上存在的IP地址。 - Romuald Brunethost = '0.0.0.0'
然后看看会发生什么? - ρss