Linux – How to ‘free’ a TCP port

linuxsockettcp

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?

Best Answer

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

Related Question