5

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?

1 Answer 1

6

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? Commented Aug 29, 2013 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 Commented Aug 29, 2013 at 14:14

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.