Windows API Reference: Network Communication

This section provides comprehensive documentation on the Windows APIs for network communication, covering both low-level socket programming and higher-level networking services.

Overview

Windows provides a robust set of APIs for network programming, enabling applications to communicate across local networks and the internet. Key technologies include Winsock (Windows Sockets API) for TCP/IP communication, and various higher-level protocols and services like HTTP, FTP, RPC, and named pipes.

Key Concepts

Winsock (Windows Sockets API)

Winsock is the standard API for network programming in Windows, based on the Berkeley Sockets API. It supports a wide range of network protocols.

Core Winsock Functions

Socket Creation and Initialization

socket(): Creates a socket.

WSAStartup(): Initializes the Winsock library.

WSACleanup(): Cleans up the Winsock library.

Connection Establishment (TCP)

connect(): Establishes a connection to a remote host.

listen(): Puts a socket into a state where it listens for incoming connections.

accept(): Accepts an incoming connection request.

Data Transfer

send(): Sends data over a socket.

recv(): Receives data from a socket.

sendto(): Sends data to a specific address (UDP).

recvfrom(): Receives data from a specific address (UDP).

Socket Options and Information

getsockopt(): Retrieves options for a socket.

setsockopt(): Sets options for a socket.

gethostbyname(): Retrieves host information by name.

getaddrinfo(): Retrieves address information for a host.

Example: Simple TCP Client

C++ Example (Conceptual)


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

int main() {
    WSADATA wsaData;
    if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
        // Handle error
        return 1;
    }

    SOCKET clientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (clientSocket == INVALID_SOCKET) {
        // Handle error
        WSACleanup();
        return 1;
    }

    sockaddr_in serverAddr;
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port = htons(8080); // Example port
    inet_pton(AF_INET, "127.0.0.1", &serverAddr.sin_addr); // Example IP

    if (connect(clientSocket, (SOCKADDR*)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR) {
        // Handle error
        closesocket(clientSocket);
        WSACleanup();
        return 1;
    }

    const char* message = "Hello, server!";
    send(clientSocket, message, strlen(message), 0);

    char buffer[1024] = {0};
    recv(clientSocket, buffer, sizeof(buffer) - 1, 0);
    // Process received data

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

Higher-Level Networking Services

Windows also offers higher-level APIs that abstract away much of the complexity of direct socket programming, such as:

Network Protocols Supported

The Windows networking stack supports a wide array of protocols, including: