How to completely destroy a socket connection in C
The close
call only marks the TCP socket closed. It is not usable by process anymore.
But kernel may still hold some resources for a period (TIME_WAIT, 2MLS etc stuff).
Setting of SO_REUSEADDR should remove binding problems.
So be sure that value of true
is really non-zero when calling setsockopt
(overflow bug may overwrite it):
true = 1;
setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,&true,sizeof(int))
There is pid
variable is your code. If you use fork
(for starting connection handling processs), then you should close sock
also in the process which does not need it.
First for the naming, so we all name the same things the same:
Server side:
The socket passed to listen()
and then to accept()
let's call the listening socket.
The socket returned by accept()
let's call the accepted socket.
Client side:
The socket passed to connect()
let's call the connecting/connected socket.
Regarding your issue:
To terminate the accept()
ed connection close the accepted socket (what you call connected) by optionally first using shutdown()
followed by close ()
.
To then accept a new connection loop right back before the call to accept()
, do not go via bind()
and listen()
again.
Only shutdown and close the listening socket if you want to get rid of pending connect()
s issued after accept()
returned.
The connection is still active because you forgot to close the connected socket. Closing the listening socket does not automatically close the connected socket.
//necessary code
close(connected); // <---- add this line
close(sock);
goto label;
I am not sure though why you are getting EADDRINUSE. The code worked fine on both linux and mac os.