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?
You want to use the
SO_REUSEADDR
option on the socket. The relevant manpage issocket(7)
. Here's an example of its usage. This question explains what happens.