MSDN Documentation

Windows API Reference

Win32 Networking APIs

The Win32 API provides a comprehensive set of functions for network programming on Windows. These APIs enable applications to communicate over various network protocols, manage network resources, and access network information.

Core Concepts

Network programming in Win32 typically involves working with sockets. A socket is an endpoint for communication. The Winsock (Windows Sockets) API is the standard interface for network programming on Windows, providing a Berkeley Sockets-like interface.

Key API Categories

  • Socket Functions: For creating, binding, connecting, sending, and receiving data.
  • Name Resolution: For resolving hostnames to IP addresses and vice versa.
  • Network Protocol Information: For querying information about network protocols and interfaces.
  • Network Management: For managing network connections and services.

Commonly Used APIs

Example Snippet (TCP Client)

Here's a basic example illustrating how to create a TCP client socket:


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

// Link with Ws2_32.lib
#pragma comment(lib, "Ws2_32.lib")

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

    // Initialize Winsock
    iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (iResult != NO_ERROR) {
        printf("WSAStartup failed with error: %d\n", iResult);
        return 1;
    }

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

    // Setup the client 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 server.
    iResult = connect(ConnectSocket, (SOCKADDR*)&clientService, sizeof(clientService));
    if (iResult == SOCKET_ERROR) {
        printf("connect failed with error: %d\n", WSAGetLastError());
        closesocket(ConnectSocket);
        WSACleanup();
        return 1;
    }

    printf("Successfully connected to server!\n");

    // ... send/recv data here ...

    // cleanup
    closesocket(ConnectSocket);
    WSACleanup();

    return 0;
}
                

Further Reading