MSDN Documentation

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

Return Value

Returns 0 on success. On failure, -1 is returned and WSAGetLastError provides the error code.

Remarks

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;
}

Related Topics