closesocket Function

The closesocket function closes an existing socket.

Syntax

int closesocket(
  SOCKET s
);

Parameters

Parameter Description
s A descriptor identifying an exported socket. The SOCKET type is an integer type.

Return Value

If no error occurs, closesocket returns zero. Otherwise, it returns SOCKET_ERROR, and a specific error number can be retrieved by calling WSAGetLastError.

Remarks

A socket can be closed by calling closesocket. If the socket is a connection-oriented socket (for example, SOCK_STREAM), closesocket will continue to send any buffered data before closing the socket. After the data is sent, the connection is terminated.

For connectionless sockets (for example, SOCK_DGRAM), closesocket is simply called, and the socket is deallocated.

If the socket descriptor s refers to a socket that has been closed, closesocket returns SOCKET_ERROR and WSAGetLastError returns WSAENOTSOCK.

When closesocket is called on a socket that has been bound to a particular network address and port, that address and port are released. If the socket is a listening socket, the process stops accepting new connections.

Any pending datagrams in the receive buffer are discarded.

Note The closesocket function is the preferred method for closing a socket when using Winsock. You should not use shutdown followed by closesocket to gracefully terminate a connection unless you have a specific reason to do so.
Important Closing a socket does not necessarily mean that all data in the receive buffer has been read. If there is data remaining in the receive buffer when closesocket is called, that data is lost.

See Also