Windows API – Network I/O

Overview

The Network I/O API for Windows provides a comprehensive set of functions for creating, configuring, and managing network communications. It includes support for sockets, address resolution, asynchronous operations, and both TCP and UDP protocols.

Key Concepts

Core Functions

NameHeaderDescription
socketwinsock2.hCreates a new socket.
bindwinsock2.hBinds a socket to a local address.
connectwinsock2.hEstablishes a connection to a remote socket.
sendwinsock2.hSends data on a connected socket.
recvwinsock2.hReceives data from a connected socket.
getaddrinfows2tcpip.hResolves hostnames to address structures.
freeaddrinfows2tcpip.hFrees address info returned by getaddrinfo.
WSAAsyncSelectwinsock2.hRequests asynchronous event notification.

Simple TCP Client Example

#include <winsock2.h>
#include <ws2tcpip.h>
#pragma comment(lib, "Ws2_32.lib")
int main() {
    WSADATA wsa;
    WSAStartup(MAKEWORD(2,2), &wsa);
    SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    struct addrinfo *result = NULL, hints = {0};
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    getaddrinfo("example.com","80",&hints,&result);
    connect(s, result->ai_addr, (int)result->ai_addrlen);
    const char *msg = "GET / HTTP/1.1\r\nHost: example.com\r\n\r\n";
    send(s, msg, (int)strlen(msg), 0);
    char buf[512];
    int bytes = recv(s, buf, sizeof(buf)-1, 0);
    buf[bytes]=0;
    printf("%s",buf);
    closesocket(s);
    WSACleanup();
    return 0;
}