Winsock (Windows Sockets) API Reference

Overview

The Winsock API provides a standard interface for network programming on Windows. It enables developers to create reliable, high‑performance network applications using TCP/IP and other protocols.

Header Files

Include the following header files in your source code to use Winsock functions:

#include <winsock2.h>
#include <ws2tcpip.h>
#include <mswsock.h>
#include <ws2spi.h>

Library

Link against the Winsock library:

ws2_32.lib

Functions

Key Winsock functions include:

FunctionDescription
WSAStartupInitializes Winsock DLL.
WSACleanupTerminates Winsock usage.
socketCreates a socket.
bindAssociates a local address with a socket.
listenMarks socket as passive for incoming connections.
acceptAccepts an incoming connection.
connectEstablishes a connection to a remote socket.
sendSends data on a connected socket.
recvReceives data from a connected socket.
getsockoptRetrieves socket options.
setsockoptSets socket options.
selectMonitors multiple sockets for activity.

Structures

Commonly used structures:

struct sockaddr_in {
    short            sin_family;   // AF_INET
    unsigned short   sin_port;     // Port number
    struct in_addr   sin_addr;     // IPv4 address
    char             sin_zero[8];
};

struct fd_set {
    u_int fd_count;                 // Number of descriptors
    SOCKET fds[FD_SETSIZE];         // Descriptor array
};

Constants

Important constants for Winsock:

#define INVALID_SOCKET (SOCKET)(~0)
#define SOCKET_ERROR   (-1)
#define AF_INET        2
#define SOCK_STREAM    1
#define SOCK_DGRAM     2
#define IPPROTO_TCP    6
#define IPPROTO_UDP    17

Sample Code

Simple TCP client example:

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

int main() {
    WSADATA wsa;
    SOCKET sock;
    struct sockaddr_in server;

    WSAStartup(MAKEWORD(2,2), &wsa);
    sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    server.sin_family = AF_INET;
    server.sin_port   = htons(8080);
    inet_pton(AF_INET, "127.0.0.1", &server.sin_addr);
    connect(sock, (struct sockaddr*)&server, sizeof(server));
    send(sock, "Hello, server!", 14, 0);
    char buffer[512];
    int bytes = recv(sock, buffer, sizeof(buffer)-1, 0);
    if (bytes > 0) {
        buffer[bytes] = '\\0';
        printf("Received: %s\\n", buffer);
    }
    closesocket(sock);
    WSACleanup();
    return 0;
}

See Also