Python socket doesn't close connection properly

You are experiencing the TIME_WAIT state of connected sockets. Even though you've closed your socket, it still has lingering consequences for a couple minutes. The reasons for this, as well as a socket flag you can set to disable the behavior (SO_REUSEADDR), are explained in the UNIX guide socket FAQ.

In short,

server = socket.socket()
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind(...)
...

Try adding import sys and terminating your app with sys.exit(). The socket stays reserved until the system is satisfied that the application is closed. You can be explicit about that with sys.exit()

[edit]Oh, ok. I am pretty new to sockets myself. So you are saying that this sequence is not safe? I cant imagine any other way to do it. You have to close your app at some point, with some technique, right? How is it correctly done then?

server.shutdown(socket.SHUT_RDWR) 
server.close()
sys.exit()