Description
Close a socket.
#include <winsock.h>
int FAR PASCAL closesocket ( SOCKET s);
s
Remarks
This function closes a socket. More precisely, it releases the socket descriptor s, so that further references to s will fail with the error WSAENOTSOCK. If this is the last reference to the underlying socket, the associated naming information and queued data are discarded.
The semantics of closesocket() are affected by the socket options SO_LINGER and SO_DONTLINGER as follows:
Option Interval Type of close Wait for close?--------------- --------------- ----------------------- ---------------- SO_DONTLINGER Don't care Graceful No SO_LINGER Zero Hard No SO_LINGER Non-zero Graceful Yes
If SO_LINGER is set (i.e. the l_onoff field of the linger structure is non-zero; see Socket Options, getsockopt() and setsockopt()) with a zero timeout interval (l_linger is zero), closesocket() is not blocked even if queued data has not yet been sent or acknowledged. This is called a "hard" close, because the socket is closed immediately, and any unsent data is lost. Any recv() call on the remote side of the circuit can fail with WSAECONNRESET.
If SO_LINGER is set with a non-zero timeout interval, the closesocket() call blocks until the remaining data has been sent or until the timeout expires. This is called a graceful disconnect. Note that if the socket is set to non-blocking and SO_LINGER is set to a non-zero timeout, the call to closesocket() will fail with an error of WSAEWOULDBLOCK. If SO_DONTLINGER is set on a stream socket (i.e. the l_onoff field of the linger structure is zero; see Socket Options, getsockopt() and setsockopt()), the closesocket() call will return immediately. However, any data queued for transmission will be sent if possible before the underlying socket is closed. This is also called a graceful disconnect. Note that in this case the Windows Sockets implementation may not release the socket and other resources for an arbitrary period, which may affect applications which expect to use all available sockets.
Return Value
If no error occurs, closesocket() returns 0. Otherwise, a value of SOCKET_ERROR is returned, and a specific error code may be retrieved by calling WSAGetLastError()
Error Codes
WSANOTINITIALISED
See Also
accept(), socket(), ioctlsocket(), setsockopt(), WSAAsyncSelect()