How to reuse TCP listening socket immediately after it was connected at least once?

Lawrence D'Oliveiro ldo at geek-central.gen.new_zealand
Sun May 24 06:45:11 EDT 2009

In message <mailman.651.1243154739.8015.python-list at>, Igor Katson 

> I have written a socket server and some arbitrary clients. When I
> shutdown the server, and do socket.close(), I cannot immediately start
> it again cause it has some open sockets in TIME_WAIT state. It throws
> address already in use exception at me.

There's a reason for that. It's to ensure that there are no leftover packets 
floating around the Internet somewhere, that you might mistakenly receive 
and think they were part of a new connection, when they were in fact part of 
an old one.

The right thing to do is try to ensure that all your connections are 
properly closed at shutdown. That may not be enough (if your server crashes 
due to bugs), so the other thing you need to do is retry the socket open, 
say, at 30-second intervals, until it succeeds.

More information about the Python-list mailing list