Winsock API Reference

Overview

The Winsock (Windows Sockets) API provides a standardized interface for network programming on Windows. It offers support for TCP/IP, UDP, and other protocols, enabling socket-based communication for both client and server applications.

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

Functions

FunctionHeaderDescription
WSAStartupwinsock2.hInitializes Winsock library.
WSACleanupwinsock2.hTerminates Winsock usage.
socketwinsock2.hCreates a socket descriptor.
connectwinsock2.hEstablishes a connection to a remote socket.
bindwinsock2.hBinds a socket to an address.
listenwinsock2.hSets a socket to listen for incoming connections.
acceptwinsock2.hAccepts an incoming connection request.
sendwinsock2.hSends data on a connected socket.
recvwinsock2.hReceives data from a connected socket.

Structures

StructureHeaderDescription
addrinfows2def.hAddress information for socket functions.
sockaddr_inws2def.hIPv4 socket address structure.
sockaddr_in6ws2def.hIPv6 socket address structure.
WSADATAwinsock2.hContains Windows Sockets implementation details.

Constants

ConstantValueDescription
AF_INET2IPv4 address family.
AF_INET623IPv6 address family.
SOCK_STREAM1TCP socket type.
SOCK_DGRAM2UDP socket type.
IPPROTO_TCP6TCP protocol.
IPPROTO_UDP17UDP protocol.

Examples

Below is a minimal TCP client example demonstrating Winsock initialization, connection, data transfer, and cleanup.

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

int main() {
    WSADATA wsaData;
    SOCKET sock = INVALID_SOCKET;
    struct sockaddr_in server;

    WSAStartup(MAKEWORD(2,2), &wsaData);
    sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = inet_addr("93.184.216.34"); // example.com
    server.sin_port = htons(80);

    connect(sock, (struct sockaddr*)&server, sizeof(server));
    const char *msg = "GET / HTTP/1.1\r\nHost: example.com\r\n\r\n";
    send(sock, msg, (int)strlen(msg), 0);

    char buffer[512];
    int bytes = recv(sock, buffer, sizeof(buffer)-1, 0);
    if (bytes > 0) {
        buffer[bytes] = 0;
        printf("%s", buffer);
    }

    closesocket(sock);
    WSACleanup();
    return 0;
}