Why does it take up to several minutes to clean a listening TCP port after a program dies

networkingresourcestcp

If I kill a program that is listening on a TCP port, it takes up to several minutes until the port is reclaimed by the system and usable again. I've seen several Q/A mentioning this phenomenon, but without an explanation. Why does that happen, why doesn't the system reclaim the port right away? Does it also happen on another systems, such as Windows or Mac?

Best Answer

The idea behind this is to ensure you don't receive packets targeted for the previous program listening on that port. This TIME_WAIT state is defined in RFC793 as two times the maximum segment lifetime.

I don't know about other Operating Systems but I assume that all of these have some kind of similar behavior.

A workaround for this problem is to set SO_REUSEADDR on the socket which should ignore the TIME_WAIT state.

Related Question