OSError[Errno 99]-Python

2024-04-24 07:25:19 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

为什么操作系统不能用地址绑定指定的端口?


Tags: 代码import服务器clienthostforgetobject
2条回答

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

在将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_REUSEADDR选项设置为套接字:

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

相关问题 更多 >