Winsock2 API Reference

This section provides detailed documentation for the Winsock 2 (Windows Sockets version 2) API, which offers advanced networking capabilities beyond the original Winsock specification.

Overview

Winsock 2 extends the original Winsock API by providing:

Key Concepts

Understanding these concepts is crucial for effective use of the Winsock 2 API:

Core Functions

The following are some of the most frequently used Winsock 2 functions:

Socket Creation and Management

Data Transmission

Error Handling

Structures

Winsock 2 utilizes several important structures:

Structure Name Description
SOCKADDR Generic socket address structure.
SOCKADDR_IN Socket address structure for IPv4.
SOCKADDR_IN6 Socket address structure for IPv6.
WSABUF Buffer structure used for I/O operations.
WSAOVERLAPPED Structure used for overlapped I/O operations.

Example: Basic TCP Client

Here's a simplified example demonstrating how to create a TCP client socket, connect to a server, and send data.


#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>

#pragma comment(lib, "ws2_32.lib") // Link with ws2_32.lib

int main() {
    WSADATA wsaData;
    SOCKET clientSocket;
    struct sockaddr_in serverAddr;
    const char* message = "Hello from Winsock 2 client!";
    int bytesSent;

    // Initialize Winsock
    if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
        printf("WSAStartup failed: %d\n", WSAGetLastError());
        return 1;
    }

    // Create a socket
    clientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (clientSocket == INVALID_SOCKET) {
        printf("Socket creation failed: %d\n", WSAGetLastError());
        WSACleanup();
        return 1;
    }

    // Configure server address
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port = htons(8080); // Example port
    InetPton(AF_INET, _T("127.0.0.1"), &serverAddr.sin_addr.s_addr); // Example IP address

    // Connect to the server
    if (connect(clientSocket, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR) {
        printf("Connect failed: %d\n", WSAGetLastError());
        closesocket(clientSocket);
        WSACleanup();
        return 1;
    }

    printf("Connected to server.\n");

    // Send data
    bytesSent = send(clientSocket, message, strlen(message), 0);
    if (bytesSent == SOCKET_ERROR) {
        printf("Send failed: %d\n", WSAGetLastError());
    } else {
        printf("Sent %d bytes: %s\n", bytesSent, message);
    }

    // Close the socket
    closesocket(clientSocket);
    WSACleanup();

    return 0;
}
        

Note: This is a simplified example. Real-world applications should include more robust error checking, buffer management, and potentially asynchronous operations for better performance.

See Also