Winsock API Reference

Connection Establishment

Establishing a TCP connection with Winsock involves a series of well‑defined steps. Below is a concise guide that covers both client‑side and server‑side procedures.

Client‑Side Flow

  1. Initialize Winsock with WSAStartup.
  2. Create a socket using socket(AF_INET, SOCK_STREAM, IPPROTO_TCP).
  3. Resolve the server address (e.g., getaddrinfo).
  4. Connect with connect() to the server’s sockaddr_in.
  5. Check the return value – on success it returns 0; on failure use WSAGetLastError.
Client Example (C++)
#include <winsock2.h>
#include <ws2tcpip.h>
#pragma comment(lib, "Ws2_32.lib")

int main() {
    WSADATA wsaData;
    SOCKET ConnectSocket = INVALID_SOCKET;
    struct addrinfo *result = nullptr, hints;
    
    WSAStartup(MAKEWORD(2,2), &wsaData);
    
    ZeroMemory(&hints, sizeof(hints));
    hints.ai_family   = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;
    
    getaddrinfo("example.com", "80", &hints, &result);
    
    ConnectSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
    connect(ConnectSocket, result->ai_addr, (int)result->ai_addrlen);
    
    // Use ConnectSocket for send/recv...
    
    closesocket(ConnectSocket);
    WSACleanup();
    return 0;
}

Server‑Side Flow

  1. Initialize Winsock with WSAStartup.
  2. Create a listening socket (socket).
  3. Bind the socket to a local address/port via bind().
  4. Listen for incoming connections with listen().
  5. Accept a connection using accept(), which returns a new socket for the client.
  6. Optionally, set socket options (e.g., setsockopt for timeouts).
Server Example (C++)
#include <winsock2.h>
#include <ws2tcpip.h>
#pragma comment(lib, "Ws2_32.lib")

int main() {
    WSADATA wsaData;
    SOCKET ListenSocket = INVALID_SOCKET, ClientSocket = INVALID_SOCKET;
    struct addrinfo hints, *result = nullptr;
    
    WSAStartup(MAKEWORD(2,2), &wsaData);
    
    ZeroMemory(&hints, sizeof(hints));
    hints.ai_family   = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;
    hints.ai_flags    = AI_PASSIVE;
    
    getaddrinfo(NULL, "27015", &hints, &result);
    
    ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
    bind(ListenSocket, result->ai_addr, (int)result->ai_addrlen);
    listen(ListenSocket, SOMAXCONN);
    
    ClientSocket = accept(ListenSocket, NULL, NULL);
    // Use ClientSocket for send/recv...
    
    closesocket(ClientSocket);
    closesocket(ListenSocket);
    WSACleanup();
    return 0;
}

Common Pitfalls

Further Reading