# Closing Sockets !

This topic is 4363 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Quick question for everyone: I'm currently working on a network game which normally runs like a champ. However, when the game crashes I don't believe closesocket() is being called (calls to closesocket are in the NET_Shutdown area). The end result is when I start up again, the socket is in use and I can't seem to get it back unless I reboot. I tried using the SO_REUSEADDR socket option, but that's either not what I needed to do, or I'm doing it incorrectly because the problem persists. So, I guess what I'm asking is: how can I ensure when I close my program I close that socket, even when the program ends abruptly? -- Edit (Grammar) -- [Edited by - Vitus on March 15, 2006 1:56:05 PM]

##### Share on other sites
Does the process actually die when you crash? In the task manager, the process needs to actually be gone; once it is gone, the kernel closes the socket for you.

SO_REUSEADDR is required for TCP sockets to re-bind to the same port within 2 minutes or so. You have to use it before you bind(), typically right after you call socket(). You also should use it on the previous socket instance (that you're now wanting to re-use).

  SOCKET mysock = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );  checkerror( mysock );  BOOL one = 1;  int r = setsockopt( mysock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof( one ) );  checkerror( r );

##### Share on other sites
Gotcha. I'll have to check in the Task Manager next time it happens. I was just running netstat -a to check ports in use. I'm also running UDP (which I should have posted) but I am making the sockopt call right after socket(), but before bind.

Thanks for the post! =)