Winsock (Windows Sockets) API Reference
Overview
The Winsock API provides a standard interface for network programming on Windows. It enables developers to create reliable, high‑performance network applications using TCP/IP and other protocols.
Header Files
Include the following header files in your source code to use Winsock functions:
#include <winsock2.h>
#include <ws2tcpip.h>
#include <mswsock.h>
#include <ws2spi.h>
Library
Link against the Winsock library:
ws2_32.lib
Functions
Key Winsock functions include:
| Function | Description |
|---|---|
WSAStartup | Initializes Winsock DLL. |
WSACleanup | Terminates Winsock usage. |
socket | Creates a socket. |
bind | Associates a local address with a socket. |
listen | Marks socket as passive for incoming connections. |
accept | Accepts an incoming connection. |
connect | Establishes a connection to a remote socket. |
send | Sends data on a connected socket. |
recv | Receives data from a connected socket. |
getsockopt | Retrieves socket options. |
setsockopt | Sets socket options. |
select | Monitors multiple sockets for activity. |
Structures
Commonly used structures:
struct sockaddr_in {
short sin_family; // AF_INET
unsigned short sin_port; // Port number
struct in_addr sin_addr; // IPv4 address
char sin_zero[8];
};
struct fd_set {
u_int fd_count; // Number of descriptors
SOCKET fds[FD_SETSIZE]; // Descriptor array
};
Constants
Important constants for Winsock:
#define INVALID_SOCKET (SOCKET)(~0)
#define SOCKET_ERROR (-1)
#define AF_INET 2
#define SOCK_STREAM 1
#define SOCK_DGRAM 2
#define IPPROTO_TCP 6
#define IPPROTO_UDP 17
Sample Code
Simple TCP client example:
#include <winsock2.h>
#include <ws2tcpip.h>
#pragma comment(lib, "ws2_32.lib")
int main() {
WSADATA wsa;
SOCKET sock;
struct sockaddr_in server;
WSAStartup(MAKEWORD(2,2), &wsa);
sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
server.sin_family = AF_INET;
server.sin_port = htons(8080);
inet_pton(AF_INET, "127.0.0.1", &server.sin_addr);
connect(sock, (struct sockaddr*)&server, sizeof(server));
send(sock, "Hello, server!", 14, 0);
char buffer[512];
int bytes = recv(sock, buffer, sizeof(buffer)-1, 0);
if (bytes > 0) {
buffer[bytes] = '\\0';
printf("Received: %s\\n", buffer);
}
closesocket(sock);
WSACleanup();
return 0;
}