Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is port not immediately released after the socket closes?

Tags:

c

sockets

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?

like image 203
Xufeng Avatar asked Mar 21 '14 02:03

Xufeng


2 Answers

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:

  • A connection from (address a, port p) to (address b, port q) is terminated
  • A second connection from (address a, port p) to (address b, port q) is established
  • A duplicate packet from the first connection is delayed in the network and arrives at the second connection when its sequence number is in the second connection's window.

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.

like image 168
Sergey Kalinichenko Avatar answered Sep 29 '22 06:09

Sergey Kalinichenko


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).

like image 21
Arkku Avatar answered Sep 29 '22 08:09

Arkku