Razin Razin - 9 days ago 6
C Question

How to reuse port in socket server application?

I am trying to write a basic server socket program. I use the following code to bind the server socket.

/* Bind the server socket */
if (bind(serversock, (struct sockaddr *) &server, sizeof(server)) < 0)
{
perror("Failed to bind the server socket");
exit(1);
}


When I run the program for the first time, it works fine but when I run it the second time, I get this error:

error

I think when I run the program second time, it gives this error because the port was already linked to program which I run the first time. Can someone tell me how to close the port currently in use? Or suggest me something else which can solve this error.

Answer

Kill the process that binds the port:

 fuser -TERM 80/tcp #kills processes on tcp port 80 using signal SIGTERM

and start again.

TCP sockets normally aren't reusable for a while (a few minutes), unless they had the SO_REUSEADDR option set (with setsockopt) before they were bound.

(This option somewhat decreases robustness, but should be fairly safe to use in a testing environment.)