I've seen a lot of answers here that say to use close() to destroy a socket but the guide I used from msdn has me using closesocket(). I'm wondering if there is a difference and if there are reasons to use one or the other.
In both cases, I am seeing the suggestion to use shutdown() so that's all well and good.
close () is a *nix function. It will work on any file descriptor, and sockets in *nix are an example of a file descriptor, so it would correctly close sockets as well. closesocket () is a Windows-specific function, which works specifically with sockets.
The semantics of the closesocket function are affected by the socket options that set members of linger structure. If the l_onoff member of the LINGER structure is zero on a stream socket, the closesocket call will return immediately and does not receive WSAEWOULDBLOCK whether the socket is blocking or nonblocking.
The (blocking) Windows Socket 1.1 call was canceled through WSACancelBlockingCall . The socket is marked as nonblocking, but the l_onoff member of the linger structure is set to nonzero and the l_linger member of the linger structure is set to a nonzero timeout value. The closesocket function closes a socket.
The closesocket function closes an existing socket. A descriptor identifying the socket to close. If no error occurs, closesocket returns zero. Otherwise, a value of SOCKET_ERROR is returned, and a specific error code can be retrieved by calling WSAGetLastError. A successful WSAStartup call must occur before using this function.
close()
is a *nix function. It will work on any file descriptor, and sockets in *nix are an example of a file descriptor, so it would correctly close sockets as well.
closesocket()
is a Windows-specific function, which works specifically with sockets. Sockets on Windows do not use *nix-style file descriptors, socket()
returns a handle to a kernel object instead, so it must be closed with closesocket()
.
I find it rather shameful that BSD-sockets do not include specific counterpart to socket
function, which could be used anywhere - but such is life.
The last, but not the least, do not confuse shutdown
'ing a socket with closing the socket. shutdown()
stops transmission on a socket, but the socket remains in the system and all resources associated with it remain. You still need to close the socket after shutting it down.
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