Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closing a listening TCP socket in C

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?

like image 811
whoi Avatar asked Oct 04 '10 13:10

whoi


People also ask

How do I close a TCP socket?

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

Do I need to close socket in C?

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.

What does listen () do in TCP?

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.

Should you close a socket after performing operations?

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!


1 Answers

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.

like image 144
Matt Joiner Avatar answered Sep 28 '22 01:09

Matt Joiner