6
votes

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.

6
Are you sure the destructors are running? Can you put some output or a breakpoint there to see? - David Thornley
TCP is standardized "on the wire" but not at the API level. Therefore, one of the most important things when asking questions regarding TCP is to disclose the platform. - Chris Cleeland

6 Answers

3
votes

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.

4
votes

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.

2
votes

Have you set the SO_REUSEADDR option? From what you're saying, it seems not.

0
votes

Don't forget to check the return value of close. It will return 0 when the socket is successfully closed. It will return -1 if it failed.

-1
votes

Are you sure your app is not somehow still running in the background?