网络编程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。


  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值