网络编程Winsock——WSAStartup

WSAStartup 初始化,返回值为错误码(不需要再调用WSAGetLastError)。不能在DllMain中调用否则可能导致死锁。可以多次调用以获得WSADATA的信息。每一次成功的调用WSAStartup都需要调用一次WSAClearup(只有对后一次是释放已分配的必要资源,之前的则是释放内部计数)。

int WSAStartup(
  _In_   WORD wVersionRequested,//高字节:副版本号,低字节:主版本号,使用MAKEWORD(X,Y)宏来生成
  _Out_  LPWSADATA lpWSAData//
);

MSDN上关于这个函数的示例(代码源自http://msdn.microsoft.com/en-us/library/windows/desktop/ms742213%28v=vs.85%29.aspx

#define WIN32_LEAN_AND_MEAN

#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
#pragma comment(lib, "ws2_32.lib")


int __cdecl main()
{
    WORD wVersionRequested;
    WSADATA wsaData;
    int err;

    wVersionRequested = MAKEWORD(2, 2);

    err = WSAStartup(wVersionRequested, &wsaData);
    if (err != 0) 
    {
        printf("WSAStartup failed with error: %d\n", err);
        return 1;
    }

    if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2)
    {
        printf("Could not find a usable version of Winsock.dll\n");
        WSACleanup();
        return 1;
    }
    else
    {
        printf("The Winsock 2.2 dll was found okay\n");
    }

    WSACleanup();
}

略微解释下

#define WIN32_LEAN_AND_MEAN

这个宏定义在http://msdn.microsoft.com/en-us/library/windows/desktop/ms738562%28v=vs.85%29.aspx有一段描述,部分援引如下。

The Winsock2.h header file internally includes core elements from theWindows.h header file, so there is not usually an #include line for the Windows.h header file in Winsock applications. If an #include line is needed for theWindows.h header file, this should be preceded with the #define WIN32_LEAN_AND_MEANmacro. For historical reasons, theWindows.h header defaults to including the Winsock.h header file for Windows Sockets 1.1. The declarations in theWinsock.h header file will conflict with the declarations in the Winsock2.h header file required by Windows Sockets 2. The WIN32_LEAN_AND_MEANmacro prevents theWinsock.h from being included by the Windows.h header.

意思就是:

头文件Winsock2.h在内部包含了Windows.h的核心元素,因此在Winsock应用程序中通常不包含头文件Windows.h。如果需要一个#include行来包含Windows.h,那么就需要在前面包含#define WIN32_LEAN_AND_MEAN 宏。由于历史原因,头文件Windows.h默认地包含Windows Sockets 1.1版的头文件Winsock.h。在头文件Winsock.h中的声明会和Windows Socket2需要的头文件Winsock2.h中的声明冲突。WIN32_LEAN_AND_MEAN宏防止Windows.h包含Winsock.h。


你可能感兴趣的:(startup)