winSocket第一步WSAStartup

写了很多socket了,很少关注socket的第一步

#define WIN32_LEAN_AND_MEAN

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

// Need to link with Ws2_32.lib
#pragma comment(lib, "ws2_32.lib")


int __cdecl main()
{

    WORD wVersionRequested;
    WSADATA wsaData;
    int err;

/* Use the MAKEWORD(lowbyte, highbyte) macro declared in Windef.h */
    wVersionRequested = MAKEWORD(2, 2);

    err = WSAStartup(wVersionRequested, &wsaData);
    if (err != 0) {
        /* Tell the user that we could not find a usable */
        /* Winsock DLL.                                  */
        printf("WSAStartup failed with error: %d\n", err);
        return 1;
    }

/* Confirm that the WinSock DLL supports 2.2.*/
/* Note that if the DLL supports versions greater    */
/* than 2.2 in addition to 2.2, it will still return */
/* 2.2 in wVersion since that is the version we      */
/* requested.                                        */

    if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2) {
        /* Tell the user that we could not find a usable */
        /* WinSock DLL.                                  */
        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");
        

/* The Winsock DLL is acceptable. Proceed to use it. */

/* Add network programming using Winsock here */

/* then call WSACleanup when done using the Winsock dll */
    
    WSACleanup();

}

其实这段代码也不用过多关注。

WSAStartup入手:

int WSAStartup(
  WORD      wVersionRequired,
  LPWSADATA lpWSAData
);

该 调用WSAStartup函数初始化了一个进程使用Winsock DLL的使用信息

第一个参数不用关注。

typedef struct WSAData {
  WORD           wVersion;
  WORD           wHighVersion;
} WSADATA;

该 WSADATA结构包含在Windows Sockets实现信息。其他字段只是为了兼容版本。再socket2之后已经只有这两个字段有意义了。就是制定soocket的版本号。

一旦应用程序或DLL成功进行了 WSAStartup调用,它就可以根据需要继续进行其他Windows套接字调用。完成使用Winsock DLL的服务后,应用程序必须调用 WSACleanup以允许Winsock DLL释放应用程序使用的内部Winsock资源。

在每次成功调用WSAStartup函数时,应用程序都必须调用WSACleanup函数。举例来说,这意味着如果一个应用程序调用 WSAStartup 3次,则它必须调用 WSACleanup 3次。对WSACleanup的前两个调用 除了减少内部计数器外没有任何作用。该任务的最后 WSACleanup调用完成了该任务的所有必要资源重新分配。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

道格拉斯范朋克

播种花生牛奶自留田

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值