1

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.

Razin
  • 221
  • 6
  • 15

1 Answers1

3

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

Petr Skocik
  • 58,047
  • 6
  • 95
  • 142
  • I tried to kill the process that binds the port but it doesn't work. I still have to wait for few minutes to reuse the port. – Razin Nov 30 '16 at 15:04