Windows Sockets (Winsock) API

Introduction

The Windows Sockets (Winsock) API provides a standardized interface for network communication on the Windows platform. It supports both TCP and UDP protocols, asynchronous I/O, and advanced socket options.

Initialization

Before using any socket functions, the Winsock library must be initialized with WSAStartup and terminated with WSACleanup.

#include <winsock2.h>
#pragma comment(lib, "Ws2_32.lib")

int main() {
    WSADATA wsaData;
    int result = WSAStartup(MAKEWORD(2,2), &wsaData);
    if (result != 0) {
        printf("WSAStartup failed: %d\n", result);
        return 1;
    }

    // ... socket code ...

    WSACleanup();
    return 0;
}

Creating Sockets

Use socket() to create a new socket descriptor.

SOCKET sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock == INVALID_SOCKET) {
    printf("socket failed: %ld\n", WSAGetLastError());
    WSACleanup();
    return 1;
}

Binding

For server sockets, bind the socket to a local address and port.

struct sockaddr_in service;
service.sin_family = AF_INET;
service.sin_addr.s_addr = inet_addr("0.0.0.0");
service.sin_port = htons(8080);

if (bind(sock, (SOCKADDR*)&service, sizeof(service)) == SOCKET_ERROR) {
    printf("bind failed: %ld\n", WSAGetLastError());
    closesocket(sock);
    WSACleanup();
    return 1;
}

Communication

Example of a simple TCP echo server.

listen(sock, SOMAXCONN);
printf("Server listening on port 8080...\n");

SOCKET client = accept(sock, NULL, NULL);
if (client == INVALID_SOCKET) {
    printf("accept failed: %ld\n", WSAGetLastError());
    closesocket(sock);
    WSACleanup();
    return 1;
}

char recvbuf[512];
int recvlen;
while ((recvlen = recv(client, recvbuf, sizeof(recvbuf), 0)) > 0) {
    send(client, recvbuf, recvlen, 0);
}
closesocket(client);
closesocket(sock);

Cleanup

Always close sockets with closesocket() and call WSACleanup() when done.

Reference

FunctionDescription
socket()Create a socket.
bind()Assign a local address to a socket.
listen()Mark socket as passive.
accept()Accept incoming connection.
connect()Initiate a connection.
send()Transmit data.
recv()Receive data.
closesocket()Close socket descriptor.