My program bind a port for listening, after it terminates, the port is not available for about a moment and any attempt to open the same port again for listening will fail in that period of time. I need to wait for a while to reopen the port.

I will need to repeatedly bind the port, because I need to retest my server program repeatedly. Is there any linux commands that can release the port prematurely, or any programming code to do the same thing? I code in C++ and uses the gSOAP framework.

Basically I will bind the port using

soap_bind(&newsoap, NULL, 13518, 100);

which I bind the server to listen on port 13518.

Ubuntu version: 11.10

I have tried the same code in Windows, and the port is immediately available after the program terminate. Do I need to do some extra steps in linux to unbind the port before it terminates?


You need to bind with the SO_REUSEADDR socket option to allow the subsequent bind to succeed. In your case:

newsoap.bind_flags |= SO_REUSEADDR;
soap_bind(&newsoap, NULL, 13518, 100);
  • From what I have read, there seems to be some security issues on using SO_REUSEADDR, where multiple programs can bind on this same port? Is is recommended to use it, or is it only good for testing purposes? – Wong Wai Jie Feb 29 '12 at 10:17
  • Are you actually worried about rogue programs running on that machine stealing your port? If so, what are you doing now to stop those programs from starting first? Most likely, it addresses this case too. (You don't need a lock on the window if the door is wide open.) – David Schwartz Feb 29 '12 at 10:19
  • Not really, I guess this would be a good solution for my problem then. Thanks for your help. – Wong Wai Jie Feb 29 '12 at 10:25

You have to close the socket. It is a security feature, that an open port will get locked by the kernel for some time.

I dont know your framework, you have to look at its docs how to close a port with it. I only used the direct kernel calls to use ports.

You might want to read the manpages of socket bind listen and some more of the pages referenced to actually understand how this works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.