Socket error: Address already in use

后端 未结 3 1806
醉梦人生
醉梦人生 2021-02-02 03:55

I have a CherryPy script that I frequently run to start a server. Today I was having to start and stop it a few times to fix some bugs in a config file, and I guess the socket

相关标签:
3条回答
  • 2021-02-02 04:07

    You could find the process and kill it by doing:

    ps aux | grep python
    

    , finding the process ID, and stopping it manually by doing:

    sudo kill -9 PID
    

    replacing PID with your PID.

    I often have to do this while testing with Flask/CherryPy. Would be interested to see if there's an easier way (for e.g. to prevent it in the first place)

    0 讨论(0)
  • 2021-02-02 04:10

    Much more easier to do it by:

    Check the PID(:5000 is the host since I've been running on 127.0.0.1:5000):
    $ lsof -i :5000
    Then kill it:
    $ sudo kill -9 PID

    0 讨论(0)
  • 2021-02-02 04:24

    You can try the following

    from socket import *
    
    sock=socket()
    sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
    # then bind
    

    From the docs:

    The SO_REUSEADDR flag tells the kernel to reuse a local socket in TIME_WAIT state, without waiting for its natural timeout to expire.

    Here's the complete explanation:

    Running an example several times with too small delay between executions, could lead to this error:

    socket.error: [Errno 98] Address already in use

    This is because the previous execution has left the socket in a TIME_WAIT state, and can’t be immediately reused.

    There is a socket flag to set, in order to prevent this, socket.SO_REUSEADDR:

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind((HOST, PORT))
    
    0 讨论(0)
提交回复
热议问题