closesocket and shutdown [Archive] - C Board

PDA

View Full Version : closesocket and shutdown


Hunter2
08-01-2003, 06:31 PM
Ok, this has been bothering me for a while. I read on MSDN that you should always call closesocket() after you create a socket using socket(). So I do it. But what I would like to know, is can the socket be re-opened, or does a new socket have to be created? Like, can I do this:

SOCKET s = socket(...);
connect(s, ...);
closesocket(s);

connect(s, ...); //Is this ok?
(...)

//Or do I have to do this
SOCKET s = socket(...);
connect(s, ...);
closesocket(s);

SOCKET s2 = socket(...);
connect(s2, ...);
(...)
If not, would it work if I used shutdown() instead?

**EDIT**
Also, am I right that closesocket() will cause the other end to get a recv() of 0 bytes?

johnnie2
08-03-2003, 11:49 AM
Invoking closesocket() on a particular socket cancels any active connection and causes the operating system to discard internally-managed data regarding the socket. After the call, the unfortunate socket has effectively been wiped out of existence; Winsock has no memory of the socket and will insist that the handle does not describe a valid socket if used in further network calls. As a result, calling closesocket() renders the afflicted socket unusable.

However, it is possible to sever an active connection without allowing the operating system to discard the socket entirely via DisconnectEx(). Unfortunately, DisconnectEx() is available under only Windows XP; you'll most likely be forced to use the second code sample to completely discard a socket and declare a new handle.
Originally posted by Hunter2
Also, am I right that closesocket() will cause the other end to get a recv() of 0 bytes?Yes; closesocket() will implicitly terminate an active connection, and the remote peer will receive zero bytes. Invoking shutdown() on a socket results in similar behavior.

Hunter2
08-03-2003, 01:53 PM
Heh, I actually posted this because of a bug I had where the server would "close" the socket but the client wouldn't know that it was closed, but I found out that it was just a bug in my socket wrapper class. Thanks anyways though, it's good to finally be sure about what closesocket() does :)