Winsock Initialization

This section details the functions and procedures for initializing and cleaning up the Windows Sockets API (Winsock).

Overview

Before an application can use Windows Sockets, it must initialize the Winsock DLL. This involves calling the WSAStartup function. Conversely, before an application terminates, it should call the WSACleanup function to release any resources allocated by the Winsock DLL.

Key Functions

WSAStartup

The WSAStartup function initiates the use of the Winsock DLL. The application calls this function once for each use of the Winsock functionality. The system maintains a count of how many times WSAStartup has been called.

int WSAStartup(
      WORD                 wVersionRequested,
      LPWSADATA            lpWSAData
    );

Parameters:

Return Value: If the function succeeds, the return value is zero. Otherwise, the return value is one of the Winsock error codes.

WSACleanup

The WSACleanup function terminates the use of the Winsock DLL. The application must call WSACleanup for every successful call to WSAStartup. When the count of calls to WSAStartup reaches zero, the Winsock DLL is unloaded from memory.

int WSACleanup(void);

Return Value: If the function succeeds, the return value is zero. Otherwise, the return value is one of the Winsock error codes.

WSADATA Structure

The WSADATA structure receives information about a particular Windows Sockets implementation.

typedef struct WSAData {
      WORD           wVersion;
      WORD           wHighVersion;
      char           szDescription[WSADESCRIPTION_LEN + 1];
      char           szSystemStatus[WSASYS_STATUS_LEN + 1];
      unsigned short iMaxSockets;
      unsigned short iMaxUdpDg;
      char           far *lpVendorInfo;
    } WSADATA, *LPWSADATA;

Common Initialization Errors

Note: Version Mismatch

Ensure that the wVersionRequested parameter in WSAStartup matches a version supported by the installed Winsock DLL. A common issue is requesting a version that is too high.

Warning: Forgetting WSACleanup

Failure to call WSACleanup can lead to resource leaks and instability. Always pair WSAStartup with WSACleanup.

Example Usage

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

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

int main() {
    WSADATA wsaData;
    int iResult;

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

    printf("Winsock initialized successfully.\n");
    printf("Version: %s\n", wsaData.szVersion);
    printf("Description: %s\n", wsaData.szDescription);

    // ... perform Winsock operations ...

    // Clean up Winsock
    WSACleanup();
    printf("Winsock cleaned up.\n");

    return 0;
}