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?
The standard way to close TCP sessions is to send a FIN packet, then wait for a FIN response from the other party. B can now send a FIN to A and then await its acknowledgement (Last Ack wait).
Note: All sockets should be closed before the end of your process. For AF_INET and AF_INET6 stream sockets (SOCK_STREAM) using SO_LINGER socket option, the socket does not immediately end if data is still present when a close is issued.
The listen() call indicates a readiness to accept client connection requests. It transforms an active socket into a passive socket. Once called, socket can never be used as an active socket to initiate connection requests. Calling listen() is the third of four steps that a server performs to accept a connection.
In conclusion, not closing a socket may lead to several problems which are more or less important. Generally you can expect more problems with TCP than UDP. You should definitely close sockets if possible when you are done with them!
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.
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