Windows API Documentation

Networking Fundamentals

Understanding networking on Windows is essential for building robust applications that communicate over networks. This guide covers the core concepts, APIs, and best practices.

Overview

Windows provides a rich set of networking APIs ranging from low‑level socket programming to high‑level HTTP client libraries. Key components include:

Winsock (Socket Programming)

Winsock follows the Berkeley sockets model with Windows‑specific extensions.

int main() {
    WSADATA wsaData;
    WSAStartup(MAKEWORD(2,2), &wsaData);
    SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    struct sockaddr_in server = {0};
    server.sin_family = AF_INET;
    server.sin_port = htons(80);
    inet_pton(AF_INET, "93.184.216.34", &server.sin_addr);
    connect(s, (SOCKADDR*)&server, sizeof(server));
    const char *msg = "GET / HTTP/1.1\r\nHost: example.com\r\n\r\n";
    send(s, msg, (int)strlen(msg), 0);
    char buf[1024];
    int received = recv(s, buf, sizeof(buf)-1, 0);
    buf[received] = 0;
    printf("%s", buf);
    closesocket(s);
    WSACleanup();
    return 0;
}

WinHTTP – HTTP Client

WinHTTP simplifies HTTP calls with built‑in handling of redirects, proxy, and TLS.

#include <windows.h>
#include <winhttp.h>

int main() {
    HINTERNET hSession = WinHttpOpen(L"Example/1.0", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
    HINTERNET hConnect = WinHttpConnect(hSession, L"example.com", INTERNET_DEFAULT_HTTP_PORT, 0);
    HINTERNET hRequest = WinHttpOpenRequest(hConnect, L"GET", L"/", NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, 0);
    WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0);
    WinHttpReceiveResponse(hRequest, NULL);
    DWORD dwSize = 0;
    while (WinHttpQueryDataAvailable(hRequest, &dwSize) && dwSize) {
        BYTE *buffer = (BYTE*)malloc(dwSize);
        DWORD dwRead = 0;
        WinHttpReadData(hRequest, buffer, dwSize, &dwRead);
        fwrite(buffer, 1, dwRead, stdout);
        free(buffer);
    }
    WinHttpCloseHandle(hRequest);
    WinHttpCloseHandle(hConnect);
    WinHttpCloseHandle(hSession);
    return 0;
}

Best Practices