Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have some code that listens to a specific TCP port. However, when I stop this code and restart it quickly afterwards, I see the error

ERROR: could not bind to socket on

If I wait a minute or so, suddenly this port is 'free' and the code runs again.

My question: Is there a way to force this particular port 'free'? To be able to start my code right away, without waiting a minute or so?

share|improve this question

You can use SO_REUSEADDR

int optval = 1;
/* create socket using socket */
setsockopt(s1, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval);
/* bind socket */

You get this error because the TCP protocol forces the server to put the socket that you just closed into the status TIME_WAIT for the time defined in net.ipv4.tcp_fin_timeout. This is to ensure that really every packet which the other peer might have sent after your server closed the socket is still being handled correctly.

Here is a nice description of this problem in the top answer of the thread: What is the meaning of SO_REUSEADDR (setsockopt option) - Linux?.

share|improve this answer
Is there a way to end the status TIME_WAIT for a socket by using just pure linux commands, without changing some code or so? – Alex Aug 29 '13 at 14:02
you can change the duration of net.ipv4.tcp_fin_timeout via sysctl and reduce it to a shorter time if you prefer that – mauro.stettler Aug 29 '13 at 14:14

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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