I found that by default OS does not immediately release the port that my server socket uses after the server shuts down. By giving SO_REUSEADDR
when setting up the socket can avoid this problem, but I don't understand why it's useful to hold the port for a while. If the server shuts down, the socket closes, any data transmitted to this port wouldn't be processed anyways right?
When the port is released, it goes into the TIME_WAIT
state to prevent duplicate packets that were delayed en route to the first connection to be delivered to the second connection.
Here is the situation when this could happen without TIME_WAIT
:
Here is a good answer explaining how to deal with this. Here is an article explaining how to mitigate the effects of TIME_WAIT
on busy servers.
In case of network socket someone else could set up a server on the same port immediately after it is released, and any new connections (TCP) or packets (UDP) that might have been intended for the previous server could then be “hijacked” by the new server. Or something like this could happen by accident if there are old packages still around in the network.
That being said, SO_REUSEADDR
is generally recommended to make servers restartable, and other means should be used to defend against port hijacking (the simplest method being privileged ports).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With