OSError[Errno 99]-python

OSError[Errno 99]-python,python,socketserver,Python,Socketserver,我想执行以下简单的服务器代码: 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)

我想执行以下简单的服务器代码:

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

为什么操作系统无法将指定的端口与地址绑定?

如果它使用ip地址但不使用主机名工作

127.0.0.1   localhost
127.0.1.1   your_hostname_here

# The following lines are desirable for IPv6 capable hosts
::1     ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
在将ip映射到主机名的
/etc/hosts
中应该有类似的内容

127.0.0.1   localhost
127.0.1.1   your_hostname_here

# The following lines are desirable for IPv6 capable hosts
::1     ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
您的
/etc/hostname
显然应该与上面相同

重新启动,您应该能够成功ping主机名


您还可以使用
socket.gethostbyname(socket.gethostname())
获取与主机名相反的i.p

尝试将
SO\u REUSEADDR
选项设置为套接字:

s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

您可能需要
host='0.0.0.0'
socket.gethostname()
返回主机名,而不是IP地址。我同意@ValentinLorentz的观点,您应该尝试具体说明IP或使用
0.0.0
。您的
gethostname()
似乎返回了一个IP/名称,该IP/名称未解析为您执行脚本的主机上的IP地址。您在问题中提到的代码没有生成此错误。它在Windows8和PythonV2.7上运行良好。请给我们看客户端代码也@ValentinLorentz要绑定它应该是host=IPAddress而不是host name吗?它可以提供IP地址,但不能附带提供主机名。注意:在终止进程后,端口可能需要一分钟左右的时间才能可用。不,此特定错误通常是
[Errno 48]地址已在使用中
我已检查,但此端口未使用ping主机名时会发生什么情况?100%数据包丢失,我的主机名解析为我的网络公共地址,我可以ping我的专用IP地址,但不能ping公共IP地址