TCP's primary design goal is to allow reliable data communication in the face of packet loss, packet reordering, and -- this is important -- packet duplication.
It's fairly obvious how a TCP/IP network stack deals with all this while the connection is up, but there's an edge case that happens just after the connection closes. What happens if a packet sent right at the end of the conversation is duplicated and delayed, such that the 4-way close (FINs and ACKs, both ways) packets get to the receiver first? The stack dutifully closes down its connection. Then later, the delayed duplicate packet shows up. What should the stack do?
More importantly, what should it do if the program that owned that connection immediately dies, then another starts up wanting the same IP address and TCP port number?
One option is to not allow that for at least 2 times the maximum round-trip-time for a packet. This is the default behavior of all common TCP/IP stacks. 2*RTT is between 30 and 120 seconds, typically. (This is the TIME_WAIT
period.) After that time, the stack assumes that any rogue packets have been dropped en route due to their TTL expiring, so it leaves the TIME_WAIT
state, allowing that IP/port combo to be reused.
The other option is to allow the new program to re-bind to that IP/port combo. In stacks with BSD sockets interfaces, you have to ask for this behavior by setting the SO_REUSEADDR
option before you call bind()
.
SO_REUSEADDR
is most commonly set in server programs.
A common pattern is that you change a server configuration file, and so need to kill and then immediately restart that server to make it reload its configuration. Without SO_REUSEADDR
, the bind() call will fail if there were connections to it open when you killed it, so those connections will hold the port in the TIME_WAIT
state for 30-120 seconds. The safe thing to do is wait out the TIME_WAIT
period, but in practice this isn't a big enough risk that it's worth doing that. It's better to get the server back up immediately so as to not miss any more incoming connections than necessary.