Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

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
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 –  mauro.stettler Aug 29 '13 at 14:14

Your Answer

 
discard

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.