10

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?

Xufeng
  • 6,452
  • 8
  • 24
  • 30
  • Is it a TCP socket, UDP socket, or something else? – Matt Ball Mar 21 '14 at 02:31
  • @MattBall In my particular case it's a TCP socket but I'm not sure if UDP does that as well? – Xufeng Mar 21 '14 at 02:33
  • 2
    You have read about [TCP](http://en.wikipedia.org/wiki/Transmission_Control_Protocol)?. Of special interest would be the [state diagram](http://en.wikipedia.org/wiki/File:Tcp_state_diagram_fixed_new.svg). UDP is more or less stateless. – Some programmer dude Mar 21 '14 at 02:34

2 Answers2

10

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • The second link is broken by September 2018. The PDF version of the article is at https://www.strayalpha.com/pubs/infocom99.pdf or one can use the Internet Archive https://web.archive.org/web/20170521010646/http://www.isi.edu:80/touch/pubs/infocomm99/infocomm99-web/ – mmm444 Sep 18 '18 at 07:23
  • @mmm444 Thanks! This is now fixed. – Sergey Kalinichenko Sep 18 '18 at 10:28
2

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

Arkku
  • 41,011
  • 10
  • 62
  • 84