Search code examples
pythonsocketssocketserver

Close server socket on quit/crash


I'm learning how to use sockets in python, and quite often when my program crashes or I Ctrl+C the server socket somehow stays listening on the port. This obviously stops the program from listening on that port when it starts back up again, so I have to keep changing it.

I'm guessing I need to do socket.close() somewhere, but where?


Solution

  • You could try the atexit module.

    import atexit
    
    function close_socket:
        s.close()
    
    atexit.register(close_socket)
    

    If the issue is delays in the port becoming available during testing, I would suggest setting SO_REUSEADDR which will allow the port to be bound again immediately instead of waiting for timeouts on the TCP stack.

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