Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket remains open after program has closed (C++)

Tags:

c++

sockets

bind

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.

like image 363
fresskoma Avatar asked Aug 06 '09 20:08

fresskoma


4 Answers

Use SO_REUSEADDR.

like image 188
bdonlan Avatar answered Nov 18 '22 09:11

bdonlan


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.

like image 22
Chris Cleeland Avatar answered Nov 18 '22 08:11

Chris Cleeland


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.

like image 26
Tynan Avatar answered Nov 18 '22 09:11

Tynan


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

like image 2
Geo Avatar answered Nov 18 '22 09:11

Geo