I'm currently writing a small server application, and my problem is, that when I close my app (or better, press the terminate button in eclipse), the socket sometimes stays open, so when I execute my app the next time, bind() will fail with "Address already in use". How can I properly close my sockets when the program exits? I already put
close(mySocket);
in the class destructors, but that doesn't seem to change anything.
Use SO_REUSEADDR.
Use netstat
to figure out what state your endpoint is in. My guess is that it's in either TIME_WAIT
and not fully closed. This is correct behavior for TCP, and exists to allow stray segments that might still be out in the ether to arrive and not cause problems. The duration of TIME_WAIT
is something like 2*MSL, i.e. twice the maximum lifetime of a segment on the network, thus insuring that even a segment that gets retransmitted gets properly handled.
As others have pointed out, SO_REUSEADDR
is your friend as long as the far side's endpoint is different each time. That's the common case, but sometimes people do weird things like bind a client to a specific port, and in that case you'll still end up with an EADDRINUSE
b/c TCP defines a session as both endpoints.
http://hea-www.harvard.edu/~fine/Tech/addrinuse.html should answer a lot of your questions. I tend to use SO_REUSEADDR to work around that problem.
Have you set the SO_REUSEADDR
option? From what you're saying, it seems not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With