Windows Networking API Reference

Explore the core APIs for network communication on Windows.

Introduction to Windows Networking

The Windows operating system provides a robust and comprehensive set of APIs for developing network-aware applications. These APIs enable applications to communicate over various network protocols, manage network resources, and interact with network services.

This section covers the primary networking technologies and APIs available on Windows, including:

  • Winsock (Windows Sockets API) for TCP/IP and UDP communication.
  • Raw Sockets for low-level network access.
  • Network Management APIs for querying and configuring network adapters and connections.
  • Higher-level protocols like HTTP and RPC integration.
Important: Understanding the underlying network protocols (TCP, UDP, IP) is crucial for effectively using these APIs.

Winsock (Windows Sockets API)

Winsock is the standard Windows implementation of the Berkeley sockets API. It provides a programmatic interface for network communication. It supports both connection-oriented (TCP) and connectionless (UDP) protocols.

Key Winsock Functions

  • socket(): Creates a socket.
  • bind(): Associates a local address with a socket.
  • listen(): Puts a socket into a listening mode for incoming connection requests.
  • accept(): Accepts a connection request on a listening socket.
  • connect(): Establishes a connection to a remote socket.
  • send() / recv(): Sends and receives data over a socket.
  • sendto() / recvfrom(): Sends and receives data using datagram sockets (UDP).
  • closesocket(): Closes a socket.

Example: Basic TCP Client


#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>

#pragma comment(lib, "ws2_32.lib")

int main() {
    WSADATA wsaData;
    SOCKET ConnectSocket = INVALID_SOCKET;
    struct sockaddr_in clientService;
    char buffer[512];
    int bytesSent, bytesRecv;

    // Initialize Winsock
    if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
        printf("WSAStartup failed.\n");
        return 1;
    }

    // Create a socket
    ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (ConnectSocket == INVALID_SOCKET) {
        printf("Error at socket(): %ld\n", WSAGetLastError());
        WSACleanup();
        return 1;
    }

    // Set up the sockaddr_in structure
    clientService.sin_family = AF_INET;
    clientService.sin_addr.s_addr = inet_addr("127.0.0.1"); // Target IP address
    clientService.sin_port = htons(27015); // Target port

    // Connect to the server
    if (connect(ConnectSocket, (SOCKADDR *) &clientService, sizeof(clientService)) == SOCKET_ERROR) {
        printf("connect failed: %ld\n", WSAGetLastError());
        closesocket(ConnectSocket);
        WSACleanup();
        return 1;
    }

    // Send data
    char sendBuf[] = "Hello, Server!";
    bytesSent = send(ConnectSocket, sendBuf, (int)strlen(sendBuf), 0);
    if (bytesSent == SOCKET_ERROR) {
        printf("send failed: %ld\n", WSAGetLastError());
        closesocket(ConnectSocket);
        WSACleanup();
        return 1;
    }
    printf("Bytes Sent: %ld\n", bytesSent);

    // Receive data
    bytesRecv = recv(ConnectSocket, buffer, 512, 0);
    if (bytesRecv == SOCKET_ERROR) {
        printf("recv failed: %ld\n", WSAGetLastError());
        closesocket(ConnectSocket);
        WSACleanup();
        return 1;
    }
    printf("Received: %.*s\n", bytesRecv, buffer);

    // Clean up
    closesocket(ConnectSocket);
    WSACleanup();

    return 0;
}
                    

Network Management APIs

These APIs allow applications to query and modify network configuration settings, such as IP addresses, DNS settings, and adapter status.

Key Management APIs

  • GetAdaptersInfo() / GetAdaptersAddresses(): Retrieve information about network adapters.
  • GetIpAddrTable(): Get the IP address table for the local computer.
  • GetTcpTable() / GetUdpTable(): Retrieve the TCP and UDP connection tables.

Example: Getting IP Addresses


#include <winsock2.h>
#include <iphlpapi.h>
#include <stdio.h>

#pragma comment(lib, "iphlpapi.lib")
#pragma comment(lib, "ws2_32.lib")

int main() {
    IP_ADAPTER_INFO *pAdapterInfo, *pAdapter;
    ULONG ulOutBufLen = sizeof(IP_ADAPTER_INFO);
    DWORD dwRetVal = 0;

    // Allocate memory for the adapter info
    pAdapterInfo = (IP_ADAPTER_INFO *) malloc(sizeof(IP_ADAPTER_INFO));
    if (pAdapterInfo == NULL) {
        printf("Error allocating memory needed to call GetAdaptersInfo\n");
        return 1;
    }

    // Make an initial call to GetAdaptersInfo to get the necessary size into the ulOutBufLen variable
    if (GetAdaptersInfo(pAdapterInfo, &ulOutBufLen) == ERROR_BUFFER_OVERFLOW) {
        free(pAdapterInfo);
        pAdapterInfo = (IP_ADAPTER_INFO *) malloc(ulOutBufLen);
        if (pAdapterInfo == NULL) {
            printf("Error allocating memory needed to call GetAdaptersInfo\n");
            return 1;
        }
    }

    if ((dwRetVal = GetAdaptersInfo(pAdapterInfo, &ulOutBufLen)) == NO_ERROR) {
        pAdapter = pAdapterInfo;
        while (pAdapter) {
            printf("\nAdapter Name: \t%s\n", pAdapter->AdapterName);
            printf("Description: \t%s\n", pAdapter->Description);
            printf("IP Address: \t%s\n", pAdapter->IpAddressList.IpAddress.String);
            printf("Subnet Mask: \t%s\n", pAdapter->IpAddressList.IpMask.String);
            printf("Gateway: \t%s\n", pAdapter->GatewayList.IpAddress.String);
            pAdapter = pAdapter->Next;
        }
    } else {
        printf("GetAdaptersInfo failed with error: %d\n", dwRetVal);
    }

    if (pAdapterInfo) {
        free(pAdapterInfo);
    }

    return 0;
}
                    

Advanced Topics

Raw Sockets

Provides low-level access to network protocols, allowing the creation of custom packet structures. Requires administrative privileges.

NetworkDirect

A high-performance, low-latency transport that bypasses the kernel for certain applications.

Sockets & I/O Completion Ports (IOCP)

For highly scalable and efficient asynchronous I/O operations in network servers.