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
- Socket – Endpoint for sending and receiving data.
- Winsock – Windows Sockets implementation, providing the underlying transport.
- Asynchronous I/O – Overlapped I/O for non‑blocking operations.
Core Functions
| Name | Header | Description |
|---|---|---|
| socket | winsock2.h | Creates a new socket. |
| bind | winsock2.h | Binds a socket to a local address. |
| connect | winsock2.h | Establishes a connection to a remote socket. |
| send | winsock2.h | Sends data on a connected socket. |
| recv | winsock2.h | Receives data from a connected socket. |
| getaddrinfo | ws2tcpip.h | Resolves hostnames to address structures. |
| freeaddrinfo | ws2tcpip.h | Frees address info returned by getaddrinfo. |
| WSAAsyncSelect | winsock2.h | Requests 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;
}