Closing a Socket
The Winsock API provides closesocket
to close an existing socket and free associated resources. It should be called after all pending I/O operations have completed or been cancelled.
Syntax
int closesocket(
SOCKET s
);
Parameters
- s – A descriptor identifying the socket to be closed.
Return Value
Returns 0
on success. On failure, -1
is returned and WSAGetLastError
provides the error code.
Remarks
- Calling
closesocket
does not automatically release any associated Winsock resources. CallWSACleanup
after all sockets are closed. - If the socket is bound to a port, the port becomes available for reuse after the socket is closed.
- Pending overlapped I/O operations are canceled. Completion routines will receive
WSA_OPERATION_ABORTED
.
Example
#include <winsock2.h>
#include <ws2tcpip.h>
#pragma comment(lib, "ws2_32.lib")
int main() {
WSADATA wsaData;
SOCKET ListenSocket = INVALID_SOCKET;
int iResult;
iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed: %d\n", iResult);
return 1;
}
ListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (ListenSocket == INVALID_SOCKET) {
printf("Error at socket(): %ld\n", WSAGetLastError());
WSACleanup();
return 1;
}
// ... bind, listen, accept ...
iResult = closesocket(ListenSocket);
if (iResult == SOCKET_ERROR) {
printf("closesocket failed: %d\n", WSAGetLastError());
}
WSACleanup();
return 0;
}