Windows API Reference
Sockets API
The Windows Sockets API (Winsock) provides a network programming interface that supports a wide range of networking protocols, including TCP/IP. This section details the functions, structures, and constants used for socket-based network communication on Windows.
Core Concepts
- Sockets: Endpoints for communication between processes on a network.
- Address Families: Specify the protocol suite (e.g., AF_INET for IPv4, AF_INET6 for IPv6).
- Socket Types: Define the communication semantics (e.g., SOCK_STREAM for reliable, connection-oriented communication; SOCK_DGRAM for unreliable, connectionless datagrams).
- Protocols: Specific communication protocols within an address family (e.g., IPPROTO_TCP, IPPROTO_UDP).
- Winsock DLL: The Dynamic Link Library (DLL) that implements the Winsock API.
Key Functions
| Function | Description |
|---|---|
socket() |
Creates a socket that is an endpoint for communication. |
bind() |
Associates a local address with a socket. |
listen() |
Places a socket in a state where it can accept incoming connection requests. |
accept() |
Accepts a connection on a socket. |
connect() |
Establishes a connection to a remote socket. |
send() / sendto() |
Sends data over a socket. |
recv() / recvfrom() |
Receives data from a socket. |
closesocket() |
Closes an existing socket. |
getaddrinfo() |
Retrieves address information for a specified host and service. |
freeaddrinfo() |
Frees address information previously allocated by getaddrinfo(). |
Important Structures
| Structure | Description |
|---|---|
SOCKADDR |
A generic socket address structure. |
SOCKADDR_IN |
An IPv4 socket address structure. |
SOCKADDR_IN6 |
An IPv6 socket address structure. |
WSADATA |
Contains information about the Winsock implementation. |
ADDRINFO |
Structure used by getaddrinfo() to store address information. |
Common Constants
- Address Family Constants:
AF_UNSPEC,AF_INET,AF_INET6 - Socket Type Constants:
SOCK_STREAM,SOCK_DGRAM - Protocol Constants:
IPPROTO_TCP,IPPROTO_UDP - Error Codes: Various constants starting with
WSAE...(e.g.,WSAECONNRESET,WSAETIMEDOUT)
Getting Started
A typical Winsock application follows these steps:
- Call
WSAStartup()to initialize the Winsock DLL. - Create a socket using
socket(). - (For server) Bind the socket to a local address and port using
bind(), and then listen for connections usinglisten(). - (For client) Connect to a remote server using
connect(). - Send and receive data using
send()/sendto()andrecv()/recvfrom(). - Close the socket using
closesocket(). - Call
WSACleanup()to release Winsock resources.