Using SO_REUSEADDR – What happens to previously open socket?

A socket is considered closed when the program that was using it dies. That much is handled by the OS, and the OS will refuse to accept any further communication from the dead conversation. However, if the socket was closed unexpectedly, the computer on the other end might not know that the conversation is over, and may still be attempting to communicate.

That is why there is, designed into the TCP spec, a waiting period before that same port number can be reused. Because in theory, however unlikely, it may be possible for a packet from the old conversation to arrive with the appropriate IP address, port numbers, and sequence numbers such that the receiving server mistakenly inserts it into the wrong TCP stream by accident.

The SO_REUSEADDR option overrides that behavior, allowing you to reuse the port immediately. Effectively, you’re saying: “I understand the risks and would like to use the port anyway.”

Leave a Comment