Winsock API Reference

Overview

The Windows Sockets (Winsock) API provides developers with a network programming interface for TCP/IP and other protocols. It is the standard socket API for Windows and supports both IPv4 and IPv6.

Functions

FunctionDescription
socketCreates a new socket descriptor.
bindAssociates a socket with a local address.
listenMarks a socket as a passive socket to accept incoming connections.
acceptAccepts a new incoming connection.
connectInitiates a connection on a socket.
sendSends data on a connected socket.
recvReceives data from a connected socket.
sendtoSends a datagram to a specific destination.
recvfromReceives a datagram and captures the source address.
getsockoptRetrieves a socket option.
setsockoptSets a socket option.
shutdownDisables sends and/or receives on a socket.
closesocketCloses a socket descriptor.

Structures

StructureMembers
sockaddr_insin_family, sin_port, sin_addr
sockaddr_in6sin6_family, sin6_port, sin6_flowinfo, sin6_addr, sin6_scope_id
fd_setfd_count, fd_array
timevaltv_sec, tv_usec

Constants

ConstantValue
AF_INET2
AF_INET623
SOCK_STREAM1
SOCK_DGRAM2
IPPROTO_TCP6
IPPROTO_UDP17
INVALID_SOCKET~0U
SOCKET_ERROR-1

Example – Simple TCP Client

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

int main() {
    WSADATA wsaData;
    SOCKET ConnectSocket = INVALID_SOCKET;
    struct sockaddr_in clientService;

    WSAStartup(MAKEWORD(2,2), &wsaData);

    ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    clientService.sin_family = AF_INET;
    clientService.sin_addr.s_addr = inet_addr("93.184.216.34"); // example.com
    clientService.sin_port = htons(80);

    connect(ConnectSocket, (SOCKADDR*)&clientService, sizeof(clientService));

    const char *sendbuf = "GET / HTTP/1.1\r\nHost: example.com\r\n\r\n";
    send(ConnectSocket, sendbuf, (int)strlen(sendbuf), 0);

    char recvbuf[512];
    int iResult = recv(ConnectSocket, recvbuf, 512, 0);
    if (iResult > 0) {
        recvbuf[iResult] = 0;
        printf("%s", recvbuf);
    }

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