【问题标题】:OSError [Errno 99] - pythonOSError [Errno 99] - python
【发布时间】:2014-05-24 08:59:05
【问题描述】:

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

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 地址。
  • 我同意@ValentinLorentz 的观点,您应该尝试具体说明IP 或使用0.0.0.0。看起来您的 gethostname() 返回的 IP / 名称无法解析为您正在执行脚本的主机上的 IP 地址。
  • 您在问题中提到的代码不会产生此错误。它在带有 python v2.7 的 Windows 8 上运行良好。请也向我们展示客户端代码!
  • @ValentinLorentz 应该是 host=IPAddress 而不是主机名才能被绑定?
  • 它适用于提供 IP 地址,但不适用于主机名

标签: python socketserver


【解决方案1】:

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

您的/etc/hosts 中应该有类似的内容,将 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

你的/etc/hostname显然应该和上面一样。

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

您也可以使用socket.gethostbyname(socket.gethostname()) 来获取 IP,而不是主机名

【讨论】:

  • 附带说明:杀死进程后端口可能需要一分钟左右才能可用。
  • 不,这个具体的错误通常是[Errno 48] Address already in use
  • 我已检查,此端口未使用
  • ping 主机名时会发生什么?
  • 100% 丢包,我的主机名解析为我的网络公共地址,我可以ping我的私有IP地址但不能ping公共地址
【解决方案2】:

尝试将SO_REUSEADDR 选项设置为套接字:

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

【讨论】:

    猜你喜欢
    • 2021-12-01
    • 2010-10-28
    • 1970-01-01
    • 2023-03-11
    • 2018-04-27
    • 2021-06-02
    • 2021-05-26
    • 2020-09-04
    • 2021-08-30
    相关资源
    最近更新 更多