Winsock Initialization and Cleanup

This section covers the essential functions for initializing and cleaning up the Windows Sockets (Winsock) environment in your application. Proper initialization and cleanup are crucial for reliable network programming.

Winsock Initialization

Before using any Winsock functions, you must initialize the Winsock library. This involves calling the WSAStartup function.

WSAStartup

Parameters

  • wVersionRequired: The Winsock version requested by the calling application.
  • lpWSAData: A pointer to a WSADATA structure that receives details about the Winsock implementation.

Return Value

  • On success, 0.
  • On failure, a non-zero Windows Sockets specific error code.

Remarks

The WSAStartup function initiates the use of the Winsock DLL. An application must successfully call WSAStartup before calling any other Winsock functions. An application can call WSAStartup multiple times. However, it must also make a corresponding call to WSACleanup for each successful call to WSAStartup.

The wVersionRequired parameter specifies the Winsock version that the application requires. The lpWSAData parameter is a pointer to the WSADATA structure that receives details about the Winsock implementation.

You must use MAKEWORD(major, minor) to construct the version number. For example, to request Winsock version 2.2, you would use MAKEWORD(2, 2).


#include <winsock2.h>
#include <ws2tcpip.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 with error: %d\n", iResult);
        return 1;
    }

    printf("Winsock initialized successfully.\n");

    // ... your network code here ...

    // Cleanup Winsock
    WSACleanup();

    return 0;
}
                

Winsock Cleanup

When your application has finished using Winsock services, it should call WSACleanup to release resources and unload the Winsock DLL.

WSACleanup

Parameters

None.

Return Value

  • If the call is successful, 0 is returned.
  • If the call fails, the return value is SOCKET_ERROR, and a specific error number can be retrieved by calling WSAGetLastError.

Remarks

WSACleanup decrements the reference count associated with successful WSAStartup calls. When the reference count reaches zero, the Winsock DLL is unloaded from memory.

It is important to call WSACleanup once for each successful call to WSAStartup to ensure proper resource management.

Related Topics