5

Suppose you have a socket listening on a TCP port, and some clients are connected. When one issues sock_close(fd) in C and tries to bind again on the same port, binding fails. Some TIME_WAIT state is seen on the "netstat -plutnoa" such as:

tcp        0      0 127.0.0.1:4567          127.0.0.1:32977         TIME_WAIT   -                timewait (17.12/0/0)

So how one can properly disconnect the server socket and reconnect on the same port immediately?

Harry Johnston
  • 35,639
  • 6
  • 68
  • 158
whoi
  • 3,281
  • 7
  • 36
  • 44

1 Answers1

9

You want to use the SO_REUSEADDR option on the socket. The relevant manpage is socket(7). Here's an example of its usage. This question explains what happens.

Sandburg
  • 757
  • 15
  • 28
Matt Joiner
  • 112,946
  • 110
  • 377
  • 526
  • A CloudFlare blog post may also supply some useful thoughts on SO_REUSEADDR. https://blog.cloudflare.com/its-crowded-in-here/ – Ron Burk Oct 02 '20 at 20:03