加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Windows > 正文

WSAStartup函数如何启动使用Winsock DLL?

发布时间:2020-12-14 01:40:37 所属栏目:Windows 来源:网络整理
导读:WSAStartup函数如何启动使用Winsock DLL? 根据文件 The WSAStartup function must be the first Windows Sockets function called by an application or DLL. It allows an application or DLL to specify the version of Windows Sockets required and ret
WSAStartup函数如何启动使用Winsock DLL?

根据文件

The WSAStartup function must be the
first Windows Sockets function called
by an application or DLL. It allows an
application or DLL to specify the
version of Windows Sockets required
and retrieve details of the specific
Windows Sockets implementation. The
application or DLL can only issue
further Windows Sockets functions
after successfully calling WSAStartup.

此函数初始化WSADATA数据结构,但在套接字编程中,我们不会将WSDATA传递给任何函数,所以该程序如何知道Windows Sockets版本和其他详细信息?

例如在这段代码中

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

void Run(int argc,char* argv[])
{
    char* host = argc < 2 ? "" : argv[1];
    struct hostent* entry = gethostbyname(host);

    if(entry)
    {
        struct in_addr* addr = (struct in_addr*) entry->h_addr;
        printf("IP Address: %sn",inet_ntoa(*addr));
    }
    else
        printf("ERROR: Resolution failure.n");
}

int main(int argc,char* argv[])
{
    WSADATA wsaData;

    if(WSAStartup(0x202,&wsaData) == 0)
    {
        Run(argc,argv);
        WSACleanup();
    }
    else
        printf("ERROR: Initialization failure.n");
}

在这个例子中,我正在使用WSAStartup()函数初始化WSADATA数据结构,之后我不会在任何地方传递wsaData.

那么我的程序如何知道wsaData的细节呢?

谢谢.

WSAStartup有两个主要目的.

首先,它允许您指定要使用哪个版本的WinSock(您在示例中请求2.2).在它填充的WSADATA中,它将根据您的请求告诉您它提供哪些版本.它还填写了您不需要查看的其他一些信息,如果您不感兴趣.您再也不必将此WSADATA结构提交给WinSock,因为它纯粹用于为您提供有关WSAStartup请求的反馈.

它的第二件事就是设置你的应用程序需要使用套接字的所有“幕后的东西”. WinSock DLL文件被加载到你的进程中,它有很多的内部结构,需要为每个进程设置.这些结构从您隐藏,但它们对您所做的每个WinSock调用都是可见的.

由于需要为使用WinSock的每个进程设置这些结构,所以每个进程必须调用WSAStartup来初始化其自身内存空间中的结构,并且在使用套接字完成WSACleanup时再次将其重新打开.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读