Socket API Reference
Overview
Functions
Structures
Constants
Examples
The Windows Socket (Winsock) API provides a standard interface for network programming on Windows platforms. It enables developers to create, configure, and manage connections over TCP/IP, UDP, and other protocols.
Key Concepts
- Socket – An endpoint for communication.
- WSAStartup – Initializes Winsock.
- bind, listen, accept – Server-side operations.
- connect, send, recv – Client-side operations.
- IOCTL, select, WSAPoll – Advanced I/O control.
Socket Functions
| Function | Description |
|---|---|
WSAStartup | Initializes Winsock library. |
WSACleanup | Terminates Winsock usage. |
socket | Creates a new socket. |
bind | Associates a socket with a local address. |
listen | Marks a socket as passive to accept connections. |
accept | Accepts an incoming connection. |
connect | Initiates a connection to a remote socket. |
send | Sends data on a connected socket. |
recv | Receives data from a connected socket. |
sendto | Sends a datagram to a specific address. |
recvfrom | Receives a datagram and captures the source address. |
setsockopt | Sets socket options. |
getsockopt | Retrieves socket options. |
select | Monitors multiple sockets for activity. |
WSAPoll | Polls sockets for events (modern alternative to select). |
ioctlsocket | Controls mode of a socket (e.g., non‑blocking). |
getsockname | Retrieves the local address of a socket. |
getpeername | Retrieves the remote address of a connected socket. |
shutdown | Disables sends and/or receives on a socket. |
Important Structures
typedef struct sockaddr_in {
short sin_family; // AF_INET
u_short sin_port; // Port number (network byte order)
struct in_addr sin_addr; // IPv4 address
char sin_zero[8];
} SOCKADDR_IN;
typedef struct in_addr {
union {
struct { BYTE s_b1,s_b2,s_b3,s_b4; } S_un_b;
struct { WORD s_w1,s_w2; } S_un_w;
ULONG S_addr;
} S_un;
} IN_ADDR;
Additional structures include WSADATA, FD_SET, and WSAPOLLFD.
Common Constants
#define AF_INET 2
#define SOCK_STREAM 1 // TCP
#define SOCK_DGRAM 2 // UDP
#define IPPROTO_TCP 6
#define IPPROTO_UDP 17
#define INVALID_SOCKET ((SOCKET)(~0))
#define SOCKET_ERROR (-1)
Simple TCP Echo Server (C++)
#include <winsock2.h>
#pragma comment(lib, "Ws2_32.lib")
int main() {
WSADATA wsa;
SOCKET listenSock, clientSock;
sockaddr_in server, client;
int clientSize = sizeof(client);
char buffer[512];
int recvSize;
WSAStartup(MAKEWORD(2,2), &wsa);
listenSock = socket(AF_INET, SOCK_STREAM, 0);
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(27015);
bind(listenSock, (sockaddr*)&server, sizeof(server));
listen(listenSock, 3);
clientSock = accept(listenSock, (sockaddr*)&client, &clientSize);
while((recvSize = recv(clientSock, buffer, sizeof(buffer), 0)) > 0) {
send(clientSock, buffer, recvSize, 0);
}
closesocket(clientSock);
closesocket(listenSock);
WSACleanup();
return 0;
}
For a full walkthrough, see the Microsoft Winsock tutorial.