The shutdown
function disables sends, receives, or both on a socket.
Syntax
int shutdown(
[in] SOCKET s,
[in] int how
);
Parameters
Parameter | Description |
---|---|
s |
A descriptor identifying a socket. |
how |
A flag that specifies the nature of the shutdown. This parameter can be one of the following values:
|
Return Value
If no error occurs, shutdown
returns zero. Otherwise, a value of SOCKET_ERROR
is returned, and a specific error code can be retrieved by calling WSAGetLastError
.
Remarks
The shutdown
function provides more control over socket closure than closesocket
.
It allows an application to close one direction of a socket while leaving the other direction open.
This can be useful for graceful connection termination.
When you call shutdown
with SD_SEND
, you indicate that your application will not send any more data.
A remote application reading from the socket will receive an FD_CLOSE
indication when all buffered data has been received.
When you call shutdown
with SD_RECEIVE
, you indicate that your application will not read any more data from the socket.
Any data that has been received by the transport provider but not yet read by the application is discarded.
When you call shutdown
with SD_BOTH
, you indicate that your application will not send or receive any more data.
This is equivalent to calling shutdown
with SD_SEND
and then with SD_RECEIVE
.
Calling shutdown
does not close the socket descriptor.
The socket descriptor is not freed until closesocket
is called.
Important Considerations
- For TCP sockets, a shutdown operation may result in sending a FIN packet.
- If the socket is connected, the
shutdown
function closes the socket gracefully. - If the socket is not connected, the
shutdown
function returns an error.
Example
The following example demonstrates how to gracefully shut down a socket for both sending and receiving.
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
// ... (socket initialization and connection code) ...
SOCKET listenSocket; // Assume this is your listening socket
// Example: Shutting down the socket for both sending and receiving
int shutdownResult = shutdown(listenSocket, SD_BOTH);
if (shutdownResult == SOCKET_ERROR) {
// Handle error, e.g., print WSAGetLastError()
int errorCode = WSAGetLastError();
// ... error handling ...
} else {
// Shutdown successful, now you might want to close the socket
closesocket(listenSocket);
}