python socket.error operation not permitted

2020-07-17 16:31发布

问题:

I am running below code as root and using python2.6.1, platform is linux

>>> import socket
>>> serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>>> serversocket.bind((socket.gethostname(), 80))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in bind
socket.error: [Errno 1] Operation not permitted

How to solve this problem

回答1:

There are several possibilities.

  • You are not root.
  • A previously run version of your application is still holding the port in the background. Kill it by name.
  • A system daemon is still holding the port, for example Apache.

Note that the port is not immediately available after the socket is closed (server having been killed). If you want to be sure that processes that don't exist anymore cannot be blocking the port from reuse, issue:

serversocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) 

before binding it.



标签: python linux