OSError [Errno 99] - python

岁酱吖の 提交于 2019-12-31 06:08:27

问题


i want to execute the following simple server code:

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

gives the following error while executing:

OSError: [Errno 99] Cannot assign requested address

why the OS cannot bind the specified port with the address?


回答1:


If it works using the ip address but not using hostname.

You should have something like this in your /etc/hosts mapping ip to hostname.

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

Your /etc/hostname should obviously be the same as above.

Reboot and you should be able to ping your hostname successfully.

You can also use socket.gethostbyname(socket.gethostname()) to get the i.p as opposed to the hostname




回答2:


Try set the SO_REUSEADDR option to the socket:

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


来源:https://stackoverflow.com/questions/23843165/oserror-errno-99-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!