4

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 0.0.0.0:7700

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?

5

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

2
  • 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
  • 1
    you can change the duration of net.ipv4.tcp_fin_timeout via sysctl and reduce it to a shorter time if you prefer that – replay Aug 29 '13 at 14:14

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.