SocketServer: getting rid of '[Errno 98] Address already in use'

rafiki_rafi picture rafiki_rafi · May 8, 2013 · Viewed 18k times · Source

I've been looking at the documentation for SocketServer. I copied the TCP server code from the documentation and it runs fine. However, I noticed that whenever I ctrl-c'ed out of the program in my terminal, and then tried to run it again, I would get the following error:

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

I looked into how to remedy the problem by reading this and this. I added the following line to my code to try to allow reuse of the address:

server.allow_reuse_address = True

I am still experiencing the same problem even with the above line added. I also added a try and except around my server.serve_forever() function, catching the KeyboardInterrupt exception and calling server.shutdown() and server.socket.close() in hopes that the address would be freed.

Here is the full extent of my TCP server code (Note: I excluded the MyTCPHandler class):

if __name__ == "__main__":
    HOST, PORT = '', 9999

    # Create the server, binding to localhost on port 9999
    server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
    server.allow_reuse_address = True

    # Activate the server; this will keep running until you
    # interrupt the program with Ctrl-C
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        server.shutdown()
        server.socket.close()

I am still getting the error running the code above and have to wait close to a minute until the address is finally freed. This is frustrating when I'm debugging and changing my code constantly.

I'm running this code using Python 2.7.3 on a RaspberryPi running Raspbian "Wheezy" 7.0.

Answer

tidy picture tidy · May 20, 2013
...
SocketServer.TCPServer.allow_reuse_address = True
server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
...

allow_reuse_address should be on the class, not on the instance.