WINSOCK 2.pdf
第3章 WinSock编程初步-Windows网络编程基础教程(第2版)-杨传栋-清华大学出版社
注意:
➢ 熟练掌握常用WinSock API函数的功能和使用方法是利用 Windows Socket进行网络编程的基础。
➢ 要掌握WinSock API函数,首先要记住该函数的名称与函 数的主要功能,其次要清楚各参数的类型及作用,以及函 数返回值的类型及意义,最后还要掌握函数成功执行的必 要条件,了解造成函数不能成功执行的常见原因。
➢ 不仅包括了Berkeley Sockets风格的库函数,同时也提供了 一套Windows所特有的扩展库函数,使程序员能够使用 Windows系统的消息驱动机制。
➢ 应用程序调用WinSock的API函数实现相互之间的通信,而 WinSock API函数又利用下层Windows操作系统中的网络 通信协议和相关的系统调用实现其通信功能。
1.包含WinSock头文件:在程序文件首部使用编译预处理命 令“#include”,将WinSock头文件包含进来。例如:
#include <WinSock2.h> 2.链接WinSock导入库,有两种方式:
✓ 通过在项目属性页中的“配置属性\链接器\输入”的 “附加依赖项”中直接添加导入库名字
✓ 在程序中使用预处理命令“#pragma comment”。例 如,程序要使用WinSock2时,可使用如下预处理命令: #pragma comment (lib, "Ws2_32.lib")
➢ 由于WinSock2完全兼容WinSock1,因此,当系统中安装 的是WinSock2时,程序中即可以使用WinSock1的头文件 和导入库也可以使用WinSock2的头文件和导入库,但如果 要使用只有WinSock2才有的功能,那就只能使用 WinSock2的头文件和导入库。
习题参考答案-Windows网络编程基础教程(第2版)-杨传栋-清华大学出版社
第1章习题1.选择题(1)答案:D(2)答案:C(3)答案:B(4)答案:C(5)答案:D(6)答案:B(7)答案:B(8)答案:D(9)答案:B(10)答案:B(11)答案:C2.填空题(1)答案:广播、单播(2)答案:路由器(3)答案:FF-FF-FF-FF-FF-FF(4)答案:目的计算机、广播地址(5)答案:路255.255.255.255、0.0.0.0(6)答案:目的端口号(7)答案:操作系统通信(8)答案:路操作系统的核心、函数库(9)答案:流式套接字、数据报套接字3.简答题(1)什么是网络协议?说出协议的三要素及它们的含义。
答:网络协议,就是指通信双方在通信时所必须遵循的用于控制数据传输的规则、标准和约定,是通信双方所使用的“语言”,它规定了有关功能部件在通信过程中的操作,定义了数据发送和数据接收的过程。
网络协议包括三方面内容。
一是“语法”,主要是指数据以及控制信息的结构或格式;第二方面内容是“语义”,它是指对构成协议的协议元素含义的具体解释;第三方面是“同步”,同步也称为“时序”,它规定了通信过程中各种事件的先后顺序。
(2)画出以太网帧结构示意图,并简要叙述以太网帧中各字段的含义。
答:以太网帧结构如下图所示:其中,目的地址,指明要接收该帧的计算机的MAC地址。
如果是一个广播帧,即该帧是广播给网络中的所有计算机的,目的地址应指明为广播地址。
源地址字段,用于指明发送该帧的计算机的MAC地址。
通过源地址,收到该帧的计算机就会知道是哪台计算机发送了该帧。
类型字段主要用于指明接收端对数据部分的处理方式,也就是说,接收端收到数据后,如果经过检验没发现错误,帧中的数据应该交给哪个程序处理。
数据字段,也被称为用户数据,是网络真正要传送的内容,长度在46~1500个字节之间。
校验码是接收方用来检查数据在传输过程中是否出错的,也称为帧校验序列(FCS),由发送方根据帧的其他部分的内容使用某种算法计算得到。
基于 WinSock 2 编写简单的客户服务器程序
“基于WinSock 2 编写简单的客户/服务器程序”一、实验目的1) 掌握基于WinSock 2 的网络通信编程。
2) 通过编写一个简单的TCP 应用程序和一个简单的UDP 应用程序,加深对客户/服务器网络交互模型的理解。
二、实验环境1) 计算机两台(已安装Windows XP 操作系统和Visual C++ 6.0 集成开发环境)。
2) 交换机一台(例如华为Quidway S3528P-EA 或者联想iSpirit2924G)。
3) 平行双绞线网线若干。
三、实验内容建立工程,设置Visual C++ 6.0 的WinSock 2 网络开发环境:1) 进入“File”→“New”→“Projects”选项卡,选择“Win32 Console Application”,在“Project name”栏中添加工程名,在“Location”栏目设置好工程存放位置后,按“OK”,在弹出窗口中选择“An empty project”,按“Finish”、“OK”后,便建立了一项新的工程。
2) 再进入“File”→“New”→“Files”选项卡,选择“C++ Source File”,在“File”栏中添加文件名,后缀为.cpp,在“Location”栏目设置好.cpp 源文件存放位置后,按“OK”,便将该.cpp 源文件添加到工程中。
3) 再进入“Project”→“Settings…”→“Link”选项卡下的“Object/library Modules”中,添加静态链接函数库ws2_32.lib,WinSock 2 网络开发环境设置完毕。
1 编写一个简单的TCP 应用程序客户端#include<Winsock2.h>#include<stdio.h>void main(){WORD wVersionRequested;WSADATA wsaData;int err;wVersionRequested = MAKEWORD( 1, 1 );err = WSAStartup( wVersionRequested, &wsaData );if ( err != 0 ) {return;}if ( LOBYTE( wsaData.wVersion ) != 1 ||HIBYTE( wsaData.wVersion ) != 1 ) {WSACleanup( );return;}SOCKET sockClient=socket(AF_INET,SOCK_STREAM,0);SOCKADDR_IN addrSrv;addrSrv.sin_addr.S_un.S_addr=inet_addr("127.0.0.1");addrSrv.sin_family=AF_INET;addrSrv.sin_port=htons(6000);connect(sockClient,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));char recvBuf[100];recv(sockClient,recvBuf,100,0);printf("%s\n",recvBuf);send(sockClient,"this is lisi",strlen("this is lisi")+1,0);closesocket(sockClient);WSACleanup();}#include <stdio.h>//socket程序需要的头文件。
Winsock2+SPI网络封包截获技术
Winsock2+SPI⽹络封包截获技术Winsock2 SPI⽹络封包截获技术2006-11-05 21:11众所周知,⽹络封包的截获技术分为⼏种,例如,过滤驱动程序,NDIS中间驱动程序以及Winsock2 SPI截取技术等等。
其中要数Winsock2使⽤最为⼴泛,下⾯就向⼤家介绍下winsock2封包截获技术——它的很⼤⼀个特点,就是Winsock2在Winsock1.1的基础上引⼊了SPI技术!Winsock2之关键函数Winsock2的函数多是以WSP开头的,他们都是在WS2_32.DLL中实现的,⽽我们熟悉的Winsock 扩展API是以WSA开头的,因为Winsock的API在SPI函数都有相互对应,你甚⾄可以把这些函数当作是API函数来使⽤。
技术实现之关键程序和其他钩⼦函数功能类似,并且将以动态链接库(DLL)⽂件实现,Winsock 钩⼦,⽤来截获 Winsock 调⽤从⽽拦截TCP/IP封包,并做相应处理。
实现DLL的安装需要修改注册表,⽽不是替换系统的DLL函数,这和过去的⼀些资料是不同的,这种⽅法通⽤性⽐较⾼!为了实际演⽰,我特别做了⼀个类似的程序,如果⼤家有⼀定基础,相信看了下⾯的⽂章后,反外挂也就不是问题了。
程序基本流程:1、系统调⽤本dll,启动WSPStartup函数;2、 WSPStartup将把30个相关函数设置成我们的函数,实现函数接挂;3、在各个函数中实现我们想要的功能,这部分读者可以随⼼所欲了!下⾯我来介绍⼏个主要核⼼函数:WSPStartup:WSPStartup是Windows Sockets应⽤程序调⽤SPI的初始化函数,我们称之为服务提供者的标准⼊⼝函数,主要是转换lpProcTable结构的30个指针设置成⾃⼰的,这样,相应的函数请求会⾸先经过我们⾃⼰的函数,然后我们⾃⼰的函数可以作适当的处理,最后再将数据流(封包)转给原来的服务提供者函数:int WSPAPI WSPStartup(WORD wVersionRequested,LPWSPDATA lpWSPData,LPWSAPROTOCOL_INFOW lpProtocolInfo,WSPUPCALLTABLE upcallTable,LPWSPPROC_TABLE lpProcTable){OutputDebugString(_T(" WSPStartup..."));TCHAR LibraryPath[512];LPWSPSTARTUP WSPStartupFunc = NULL;HMODULE hLibraryHandle = NULL;INT Error = 0;//LoadLibrary GetProcAddress我就不多说了,所有DLL⽂件都少不了的。
误删winsock和winsock2注册表的解决方案
误删winsock和winsock2注册表的解决方案全文共四篇示例,供读者参考第一篇示例:随着计算机技术的不断发展,我们常常会在使用电脑的过程中遇到各种各样的问题。
注册表错误是一种比较常见的问题之一。
今天我们要讨论的是关于误删winsock和winsock2注册表的解决方案。
让我们先了解一下winsock和winsock2是什么。
Winsock是Windows套接字的缩写,是Windows系统下用于进行网络通信的API。
而winsock2则是对winsock的进一步扩展和升级,提供更多的功能和性能。
在Windows系统中,winsock和winsock2注册表信息的正确性对于网络连接的正常运行至关重要。
如果不小心误删了winsock和winsock2的注册表信息,可能会导致网络连接无法正常工作,无法上网或者无法访问局域网等问题。
在面对这种情况时,我们可以采取以下几种解决方案来修复这个问题。
第一种解决方案是使用系统还原。
系统还原是Windows系统自带的一个功能,可以将系统恢复到之前的某个时间点,从而还原注册表信息。
你可以依次点击开始菜单-所有程序-附件-系统工具-系统还原,然后按照系统提示选择一个可以恢复注册表信息的时间点进行还原操作。
第二种解决方案是使用命令行工具修复。
你可以按下Win+R组合键打开运行窗口,输入“cmd”后按回车键,打开命令行窗口。
在命令行窗口中,输入以下命令可以重新安装winsock和winsock2的注册表信息:netsh winsock resetnetsh winsock reset catalog执行完以上命令后,重启计算机,看看网络连接是否恢复正常。
第三种解决方案是使用第三方工具修复。
如果以上两种方法都不起作用,你还可以使用一些专门的注册表修复工具来修复winsock和winsock2注册表信息。
常见的工具有CCleaner、Wise Registry Cleaner等,你可以下载安装这些工具,然后按照软件指引来修复注册表信息。
win32WinSock2网络编程socket-tcp通信
win32WinSock2⽹络编程socket-tcp通信今天复习了⼀下tcp通信的实现,写了写代码。
简单的总结⼀下:服务器作为监听者的⾓⾊需要先创建服务器socket套接字,然后使⽤bind绑定套接字和端⼝信息等等,再创建⽤于连接客户端的socket套接字,使⽤accept函数等待客户端的连接并处理。
客户端则只需要创建⽤于连接服务器的socket套接字connect函数建⽴与远程主机的链接就可以了。
同时需要注意的是错误的处理和关闭套接字等等。
服务器:1 #include<WinSock2.h>2#pragma comment(lib,"ws2_32.lib")3 #include <stdio.h>4 #include <string.h>5678int main(){9 WSADATA wsaData; // 初始化返回信息结构体10 WORD wVersion = MAKEWORD(2,2); // 制作版本号11 SOCKET hServer; // 定义套接字句柄12if (WSAStartup(wVersion, &wsaData)){ //初始化13 printf("initial failed");14return0;15 }16//in_addr addr; // ip地址结构体17//addr.s_addr = inet_addr("127.0.0.1"); // 转化字符串为32位整形ip地址18//char* lpszIp = inet_ntoa(addr); //整形转化为字符串形式1920 hServer = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); //tcp形式流式套接字21if (hServer == INVALID_SOCKET){22 printf("socket failed \n");23 }24 sockaddr_in addrServer;25 addrServer.sin_family = AF_INET;26 addrServer.sin_port = htons(8888); // 指定端⼝27 addrServer.sin_addr.s_addr = htonl(INADDR_ANY); //指定能访问的ip28int nRet = bind(hServer, (sockaddr*)&addrServer, sizeof(addrServer));29if (nRet == SOCKET_ERROR){30 printf("bind error \n");31 closesocket(hServer);32 WSACleanup();33return0;34 }35//进⾏监听36 nRet = listen(hServer,5); //最多监听5个37 printf("start listening ... \n");38if (nRet == SOCKET_ERROR){39 printf("listen error \n");40 closesocket(hServer);41 WSACleanup();42return0;43 }4445//接收客户端请求46 SOCKET hClient;47 sockaddr_in addrClient;48int nLen = sizeof(addrClient);49 hClient = accept(hServer,(sockaddr *)&addrClient, &nLen); // ?建⽴监听句柄,直到接收到请求50if (hClient == INVALID_SOCKET){51 printf("accept error \n");52 closesocket(hServer);53 WSACleanup();54return0;55 }56 printf("Get a connect! \n");57 send(hClient, "helllllllooooooo",sizeof("helllllllooooooo"), 0);5859char szBuf[255];60//循环接收客户端数据61while (1)62 {63 memset(szBuf, 0, sizeof(szBuf)); // 清空缓冲区64 nRet = recv(hClient, szBuf,sizeof(szBuf),0);65if (nRet == SOCKET_ERROR){66 printf("recv error \n");67 closesocket(hClient);68 closesocket(hServer);69 WSACleanup();70return0;71 }7273char sPrint[sizeof(szBuf)];74 sprintf(sPrint, "IP:%s, recv msg: %s ",inet_ntoa(addrClient.sin_addr),szBuf);//格式化字符串75 printf(sPrint);76if(strcmp(szBuf, "close") == 0){ // 检测退出77 nRet = send(hClient,"close",strlen("close"), 0);78break;79 }80else{81//接收到数据82 sprintf(sPrint, "the server has recved your msg: %s ", szBuf);83 nRet = send(hClient,sPrint,strlen(sPrint), 0);84if (nRet == SOCKET_ERROR){85 printf("send err \n");86 closesocket(hClient);87 closesocket(hServer);88 WSACleanup();89return0;90 }91 }929394 }95 closesocket(hClient);96 closesocket(hServer);97 WSACleanup();9899return0;100 }客户端:1 #include<WinSock2.h>2#pragma comment(lib,"ws2_32.lib")3 #include <stdio.h>4 #include <string.h>5678int main(){9 WSADATA wsaData; // 初始化返回信息结构体10 WORD wVersion = MAKEWORD(2,2); // 制作版本号11 SOCKET hClient; // 定义套接字句柄12if (WSAStartup(wVersion, &wsaData)){ //初始化13 printf("initial failed");14return0;15 }1617 hClient = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); //tcp形式流式套接字18if (hClient == INVALID_SOCKET){19 printf("socket failed \n");20 }2122 sockaddr_in addrServer;23 addrServer.sin_family = AF_INET;24 addrServer.sin_port = htons(8888); // 指定端⼝25 addrServer.sin_addr.s_addr = inet_addr("192.168.56.101"); //指定要连接的ip26//建⽴连接27int nRet = connect(hClient,(sockaddr*)&addrServer, sizeof(addrServer));28if (nRet == SOCKET_ERROR){29 printf("connect error \n");30 closesocket(hClient);31 WSACleanup();32return0;33 }34 printf("connect successsssss\n");3536char szBuf[255];37//循环接收客户端数据38while (1)39 {40 memset(szBuf, 0, sizeof(szBuf)); // 清空缓冲区41 nRet = recv(hClient, szBuf,sizeof(szBuf),0);42if (nRet == SOCKET_ERROR){43 printf("recv error \n");44 closesocket(hClient);45 WSACleanup();46return0;47 }4849char sPrint[sizeof(szBuf)];50 sprintf(sPrint, "recv msg: %s ",szBuf);//格式化字符串51 printf(sPrint);52if(strcmp(szBuf, "close") == 0){ // 检测退出53 nRet = send(hClient,"close",strlen("close"), 0);54break;55 }56else{57//接收到数据58if (strcmp(szBuf, "helllllllooooooo") == 0){59 send(hClient, "wow", sizeof("wow"),0);60 }61 }626364 }65 closesocket(hClient);66 WSACleanup();6768return0;69 }。
Windows Server 2012 R2 快速入门指南.pdf_1701126129.32377
Step 3
Deploy Windows Server 2012
Microsoft Deployment Toolkit Microsoft Deployment Toolkit (MDT) 2012 provides guidance and tools to help you quickly deploy Windows Server 2012. You can use MDT to create completely functional base servers that are ready for provisioning across an organization. You can also customize the MDT deployment process to install line-of-business applications for Windows Server 2003, Windows Server 2008, and Windows Server 2012.
--Remote Desktop Connection Broker --Remote Desktop Licensing --Remote Desktop Virtualization Host • Routing and Remote Access Server • Web Server (Internet Information Services including a subset of ) • Windows Server Update Services
NOTE: You can switch between the Server Core option and the Server with a GUI option as needed at any time later.
误删winsock和winsock2注册表的解决方案
误删winsock和winsock2注册表的解决方案如果误删了winsock和winsock2注册表,可能会导致电脑无法上网。
以下是两种可能的解决方案:方案一:手动安装TCP/IP协议1. 打开注册表编辑器,右键删除Winsock和Winsock2(若已删则跳过),路径如下:HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\Winsock HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\Winsock 22. 找到 C:\Windows\inf\文件,该文件为 tcp/ip协议文件。
3. 控制面板->网络和Internet->网络和共享中心->右键本地连接->属性。
4. 先选择TCP/IPv6->安装->协议->添加->从磁盘安装->浏览->C:\Windows\inf\>打开->确定->选择“TCP/IPv6”。
5. 选择ipv4协议重复同样的操作,最后选择TCP/IPv4,即: TCP/IPv4->安装->协议->添加->从磁盘安装->浏览->C:\Windows\inf\>打开->确定->然后选择“TCP/IPv4”。
6. 开始->Windows系统->命令提示符->管理员身份运行->输入命令netsh winsock reset->回车。
完成所有操作后,重启电脑即可。
方案二:从相同系统的其他电脑上导出一份winsock和winsock2注册表,然后在出问题的电脑上导入。
但需要注意的是,win10家庭版应该只能用这种方式,或者用其他注册表修复软件。
在安装TCP/IP协议时,win10家庭版将会被组策略拦截下来,导致无法完成安装。
WinSock 2.0网络套接字编程
第五章WinSock 2.0网络套接字编程5.1 套接字基本概念套接字是应用程序通信的基石,是支持TCP/IP协议的网络通信应用的基本操作单元。
可以将套接字看作是不同主机间的进程进行双向通信的端点:网络中两台通信的主机各自在自己机器上建立通信的端点──套接字,然后使用套接字进行数据通信。
一个套接字是如下描述的一个结构:{协议,本地地址,本地端口,远程地址,远程端口}操作系统会为本地建立的套接字分配一个唯一的套接字标识号,应用程序按该标识号来使用套接字进行网络通信。
根据网络通信的特征,套接字主要分为两类:流套接字(SOCK_STREAM)和数据报套接字(SOCK_DGRAM)。
流套接字是面向连接的,它提供双向的、有序的、无差错、无重复并且无记录边界的数据流服务,适用于处理大量数据,提供可靠的服务。
数据报套接字是无连接的,它支持双向的数据传输,具有开销小、数据传输效率高的特点,但不保证数据传输的可靠性、有序性和无重复性,适合少量数据传输、以及时间敏感的音视频多媒体数据传输。
此外,还有一种较少使用的套接字叫原始套接字(SOCK_RAW),可以使用它对底层协议如IP或ICMP直接访问,在通信与协议开发时有时会用到。
5.2 Winsock编程原理Winsock是Microsoft Windows平台上使用套接字的设施。
它实际上是一组可供应用程序进行TCP/IP通信的API应用编程接口。
Winsock分1.1版和2.x版,从Windows 98开始使用2.x版。
Winsock 2提供了一组编写网络应用程序的基本API函数,诸如创建套接字、地址绑定、侦听连接请求、发出连接请求、接受连接请求、发送和接收数据、关闭套接字,等等。
这些Winsock 2所用API函数的声明、常数等等均在头文件winsock2.h内定义,用VC++6.0开发网络应用程序时,需要在主程序开头使用#include <winsock2.h>语句,以便编译时和主程序一起参加编译。
Winsock 2 入门教程
Winsock 2 入门指南(翻译自MSDN+CBuilder2010文档)Translated by Xana HopperBlog: Email: xanahopper@一下是Windows Sockets编程的入门指南,提供帮助理解最基础的Winsock函数和数据结构,以及它们是如何一起运作。
零、关于服务器和客户端有两种截然不同网络应用程序:服务器(Servers)和客户端(Clients)。
服务器和客户端有着不同的行为,因此建立它们的过程也是不一样的,下面是建立一个TCP/IP服务器和客户端的一般模型。
服务器1.初始化Winsock2.建立一个套接字(Socket)3.绑定Socket4.在Socket上为客户端监听5.接受(Accept)一个来自客户端的连接6.接收和发送数据7.断开连接客户端1.初始化Winsock2.建立一个Socket3.连接到服务器4.发送和接收数据5.断开连接注意:对于二者来说有几步是一样的,这几步实现起来几乎完全一样,指南中这几步会具体的根据所建立程序的类型说明的。
一、建立一个基础的Winsock程序为建立一个基础的Winsock程序1.建立一个空的工程2.添加一个空的C++源文件3.确保构建环境对微软SDK的Lib、Include和Src的文件夹正确引用4.确保构建环境的连接器依赖项包含了WS2_32.lib,使用Winsock的程序必须连接此文件5.开始进行Winsock编程,通过包含Winsock2.h来使用Winsock的API。
(Winsock2.h头文件已经包含了大部分Winsock函数、数据结构和定义,Ws2tcpip.h头文件包含了在Winsock2协议兼容文档中为TCP/IP用于检索IP地址的新函数和数据结构。
Xana:括号中内容为MSDN独有,C++ Builder 2010 Document中未给与说明,不知是CB更新及时库文件做得好还是什么其他原因)#include <winsock2.h>#include <ws2tcpip.h>#include <stdio.h>int main() {return 0;}(Xana:以下还是MSDN独有,看来MS的独家历史问题不少啊)注意如果需要使用IP Helper APIs的话需要引用Iphlpapi.h头文件,当Iphlpapi.h被引用的时候,引用Winsock2.h的#include引用行应置于Iphlpapi.h行之上。
2的扩展特性
如果在应用程序提供数据缓冲区时已经有数据到来,那么接收的数据 将被立即拷贝进用户缓冲区。 如果数据到来时,应用程序没有提供接收缓冲区,那么网络将回到我 们熟悉的同步操作方式-传送来的数据将被存放进内部缓冲区,直到 应用程序发出了接收调用并且提供了接收缓冲区,这时接收的数据就 被拷贝进接收缓冲区。 这种做法会有一个例外:就是当应用程序使用 setsockopt()函数把接 收缓冲区长度置为了0。 在这种情况下,对于可靠传输协议,只有在应用程序提供了接收数据 缓冲区后,数据才会被接收; 而对于不可靠传输协议,数据将会丢失。 对于发送的一方,应用程序使用 WSASend() 函数或WSASendTo() 函数提 供一个指向已填充了数据的缓冲区的指针。应用程序不应在网络使用 完该缓冲区的数据以前以任何方式破坏该缓冲区的数据。
重叠I/O涉及的一些函数
WSACreateEvent:创建一个新的事件对象。
WSAEVENT WSACreateEvent (void); 返回值:如果函数成功,则返回值即是事件对象的句柄。如果函数失败,返回 WSA_INVALID_EVENT。应用程序可通过调用WSAGetLastError()函数获取进一步 的错误信息。 BOOL WSASetEvent( WSAEVENT hEvent );
重叠发送和接收调用会立即返回。 如果返回值是 0,那么表明了 I/O操作已经完成,对应的完成指示也已 经可以得到。 如果返回值是 SOCKET_ERROR ,并且错误代码是 WSA_IO_PENDING ,那么 表明重叠操作已经被成功地初始化,今后发送缓冲区被用完或者接收 缓冲区被填满时,将会有完成指示。 任何其他的错误代码表明了初始化没有成功,今后也不会有什么完成 指示。 发送操作和接收操作都可以被重叠使用。 接收函数可以被多次调用,发出接收缓冲区,准备接收到来的数据。 发送函数也可以被多次调用,组成一个发送缓冲区队列。 要注意的是,应用程序可以通过按顺序提供发送缓冲区来确保一系列 重叠发送操作的顺序,但是对应的完成指示有可能是按照另外的顺序 排列的。同样的,在接收数据的一方,缓冲区是按照被提供的顺序填 充的,但是完成指示也可能按照另外的顺序排列。
winsock2 recv flags参数
winsock2 recv flags参数在使用Winsock2(Windows Sockets 2)库中的`recv` 函数时,`flags` 参数表示接收操作的附加选项。
这个参数是可选的,通常可以设置为零。
以下是`recv` 函数的基本语法:```cint recv(_In_ SOCKET s,_Out_ char *buf,_In_ int len,_In_ int flags);```其中,`flags` 参数是一个整数,用于指定接收操作的附加选项。
以下是`recv` 函数中常见的一些`flags` 值:- 0(默认值):无特殊标志,通常使用0 表示普通的接收操作。
- MSG_PEEK (0x02):允许查看接收缓冲区中的数据,但不移除。
实际上,`recv` 将返回缓冲区中的数据,但是数据仍然保留在缓冲区中。
- MSG_WAITALL (0x08):如果len 大于可用数据的大小,`recv` 将等待直到接收到len 字节的数据为止。
否则,它会返回可用数据的数量。
- MSG_OOB (0x01):接收带外数据(Out-of-Band data)。
这通常与`SO_OOBINLINE` 套接字选项一起使用。
在一般情况下,大多数情况下都可以将`flags` 参数设置为0,以进行普通的接收操作。
然而,根据特定的需求,你可能需要使用上述提到的其他标志。
示例:```cchar buffer[1024];int bytesReceived = recv(socketDescriptor, buffer, sizeof(buffer), 0);```在这个示例中,`flags` 被设置为0,表示普通的接收操作。
请注意,具体的使用方式可能根据应用程序的需要而有所不同。
在编写代码时,请查阅Microsoft 文档以获取最新和详细的信息。
winsock使用手册
winsock使用手册Winsock是Windows Socket的缩写,它是一种提供网络编程接口的技术,用于在Windows操作系统上进行网络通信。
本手册将介绍Winsock的基本概念、API函数和使用方法,帮助读者快速上手Winsock编程。
一、Winsock简介Winsock是Windows操作系统提供的一种网络编程接口,它允许开发人员创建基于TCP/IP协议的应用程序,并实现网络通信。
Winsock使用C语言提供了一组API函数,方便开发者进行网络编程。
二、Winsock的基本概念1. Socket在Winsock中,Socket是一个抽象概念,代表一个网络通信的端口。
开发者可以通过创建Socket建立与其他计算机的连接,并发送和接收数据。
2. 协议族Winsock支持多种协议族,常用的有AF_INET(用于互联网通信)和AF_INET6(用于IPv6通信)。
3. 协议类型协议类型定义了数据传输的特性,常见的协议类型有SOCK_STREAM(流式套接字,提供可靠的、面向连接的通信)和SOCK_DGRAM(数据报套接字,提供无连接的通信)。
4. IP地址与端口在Winsock中,IP地址用于标识网络上的计算机,端口用于标识一个应用程序,在计算机上可以同时运行多个应用程序,通过端口来区分不同的应用程序。
三、Winsock API函数1. WSAStartupWSAStartup函数用于初始化Winsock库,并指定所需的版本。
2. socketsocket函数用于创建一个套接字,返回一个套接字描述符。
3. bindbind函数用于将一个套接字与特定的IP地址和端口绑定。
4. listenlisten函数用于使一个套接字进入监听状态,等待客户端的连接。
5. acceptaccept函数用于接受客户端的连接请求,并创建一个新的套接字用于与客户端进行通信。
6. connectconnect函数用于与服务器建立连接。
Mellanox WinOF-2 产品知识库说明书
Mellanox Technologies Mellanox WinOF-2 Known IssuesLast Updated: 01 March 2018Mellanox Technologies350 Oakmead Parkway Suite 100Sunnyvale , CA 94085U.S.A.Tel: (408) 970-3400Fax: (408) 970-3403© Copyright 2018. Mellanox Technologies Ltd. All Rights Reserved.Mellanox®, Mellanox logo, Accelio®, BridgeX®, CloudX logo, CompustorX®, Connect -IB®, ConnectX®, CoolBox®, CORE-Direct®, EZchip®, EZchip logo, EZappliance®, EZdesign®, EZdriver®, EZsystem®, GPUDirect®, InfiniHost®, InfiniBridge®, InfiniScale®, Kotura®, Kotura logo, Mellanox CloudRack®, Mellanox CloudXMellanox®, Mellanox Federal Systems®, Mellanox HostDirect®, Mellanox Multi-Host®, Mellanox Open Ethernet®, Mellanox OpenCloud®, Mellanox OpenCloud Logo®, Mellanox PeerDirect®, Mellanox ScalableHPC®, Mellanox StorageX®, Mellanox TuneX®, Mellanox Connect Accelerate Outperform logo , Mellanox Virtual Modular Switch®, MetroDX®, MetroX®, MLNX-OS®, NP-1c®, NP-2®, NP-3®, NPS®, Open Ethernet logo , PhyX®, PlatformX®, PSIPHY®, SiPhy®, StoreX®, SwitchX®, Tilera®, Tilera logo, TestX®, TuneX®, The Generation of Open Ethernet logo , UFM®, Unbreakable Link®, Virtual Protocol Interconnect®, Voltaire® and Voltaire logo are registered trademarks of Mellanox Technologies , Ltd.All other trademarks are property of their respective owners .For the most updated list of Mellanox trademarks, visit /page/trademarksNOTE:THIS HARDWARE, SOFTWARE OR TEST SUITE PRODUCT (“PRODUCT(S)”) AND ITS RELATED DOCUMENTATION ARE PROVIDED BY MELLANOX TECHNOLOGIES “AS -IS” WITH ALL FAULTS OF ANY KIND AND SOLELY FOR THE PURPOSE OF AIDING THE CUSTOMER IN TESTING APPLICATIONS THAT USE THE PRODUCTS IN DESIGNATED SOLUTIONS. THE CUSTOMER'S MANUFACTURING TEST ENVIRONMENT HAS NOT MET THE STANDARDS SET BY MELLANOX TECHNOLOGIES TO FULLY QUALIFY THE PRODUCT(S) AND/OR THE SYSTEM USING IT . THEREFORE, MELLANOX TECHNOLOGIES CANNOT AND DOES NOT GUARANTEE OR WARRANT THAT THE PRODUCTS WILL OPERATE WITH THE HIGHEST QUALITY. ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY , FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT ARE DISCLAIMED. IN NO EVENT SHALL MELLANOX BE LIABLE TO CUSTOMER OR ANY THIRD PARTIES FOR ANY DIRECT, INDIRECT, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES OF ANY KIND (INCLUDING, BUT NOT LIMITED TO, PAYMENT FOR PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY FROM THE USE OF THE PRODUCT(S) AND RELATED DOCUMENTATION EVEN IF ADVISED OF THE POSSIBILITY OF SUCHDAMAGE.Doc #: N/A 2Mellanox TechnologiesRev 1.03Mellanox Technologies Table of ContentsTable of Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3List Of Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4Chapter 1 Archived Known Issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5Rev 1.04Mellanox Technologies List Of TablesTable 1:Archived Known Issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5Archived Known Issues Rev 1.05Mellanox Technologies 1Archived Known IssuesThe following table describes archived known issues in the former releases on WinOF-2.Table 1 - Archived Known Issues (Sheet 1 of 5)Internal Ref.Issue1121688Description: Mellanox WinOF-2 Device Diagnostics and Mellanox WinOF-2 PCI Device Diag-nostics counters in Perfmon are available only on the adapter that was initialized first, which is thecounters’ owner.In case both adapters are viewed in Perfmon:1. The owner will receive correct values, while the second adapter will only receive zeros.2. If the owner goes down, the ownership will move to the second adapter.Workaround : N/AKeywords: WinOF-2 Device Diagnostics, Mellanox WinOF-2 PCI Device Diagnostics, Perfmon,ownershipDetected in version: 1.70.0.1961251Description: On a dual port device, when the first port is IPoIB and the second port is Ethernet, thedevice will not start over iSCSI and Windows 2012 in the Ethernet port.Workaround : N/AKeywords: IPoIB port, Ethernet port, ISCSI, Windows 2012Detected in version: 1.701000390Description: Configuring a different RoCE mode between VF and PF is not supportedWorkaround : N/AKeywords: RoCE, VF, PFDetected in version: 1.70917856Description: All folders under %PROGRAMFILES%Mellanox\MLNX_WINOF2 are deleted incase of upgrade failure. The old driver remains, and no connectivity loss should occur. The issueoccurs only when the upgrade fails after the old version was removed.Workaround : Following the upgrade failure, reinstall the new package folder.Keywords: Installation, setup, missing foldersDetected in version: 1.70915981Description: On IPoIB adapters, the network adapter and task manager network counters count allport traffic when only non-RDMA traffic should be shown.Workaround : N/AKeywords: IPoIB, counters, RDMADetected in version: 1.60939227Description: When upgrading from WinOF-2 1.50 to 1.60 or later, the MAC address used for theIPoIB interface changes.Workaround : N/AKeywords: IPoIB, MAC addressDetected in version: 1.60Rev 1.06Mellanox Technologies 928999Description: When installing a new driver, driver version queries via WMI may not be up-to-date,due to information caching in the WMI service.Workaround : Stop and restart the WMI service, running the following CMD commands:net stop winmgmtnet start winmgmtKeywords: Driver version queries, WMI, information cachingDetected in version: 1.60964973Description: SRQ limit event is not supported in the ND and NDK RDMA programming inter-faces.Workaround : N/AKeywords: SRQ, ND, NDK RDMADetected in version: 1.60900928Description: The packet sniffer is currently not supported in InfiniBand mode.Workaround : N/AKeywords: InfiniBand, packet snifferDetected in version: 1.50-Description: The installation process or restart of the driver does not close any RoCE userspace applications running in the background, and may cause a bug check as a result of a stuckcmdWorkaround : It is recommended to close all running RoCE user space applications prior toupgrading the driver.Keywords: Installation/Upgrade-Description: Installation/upgrade fails due to PNP failure to copy the driver files to the driverstore, and the following text is printed in the event logs: Fault bucket, type 0Event Name: PnPDriverImportError Response: Not availableAttached Files: C:\Users\<user>\AppData\Local\Temp\DMI151A.tmp.log.xmlC:\Program Files\Mellanox\ MLNX_WinOF2\Drivers\”Current OS”\mlx5.infWorkaround : Reboot the machine and reinstall.Keywords: Installation/Upgrade-Description: Installing both WinOF for ConnectX-3 and ConnectX-3 Pro, and WinOF-2 forConnectX-4 is supported only from WinOF version 5.00 and above.Workaround : N/AKeywords: Installation/UpgradeTable 1 - Archived Known Issues (Sheet 2 of 5)Internal Ref.IssueArchived Known Issues Rev 1.07Mellanox Technologies 654674Description: When trying to uninstall the mlx5 driver manually (by using pnputil/DPINST orDIFX API), additional hardware scan will be required before viewing the device in the DeviceManager or before reinstalling.This used to happen due to a bug in the NetCfgx.dll.(Microsoft case ID is: 115020112345121).Workaround : Rescan the hardware after performing the uninstallation.Keywords: Installation/Upgrade650489Description: While installing the driver on Windows Server 2012, and if SR-IOV mode isdisabled in the BIOS and enabled in the firmware, the server might reboot, and the BIOS willhang while loading.Workaround : To work in SR-IOV mode, enable SR-IOV in BIOS. Otherwise, disable SR-IOV in the firmware using mlxconfig.For further information on how to enable/disbale SR-IOV, please refer to the “Single Root I/OVirtualization (SR-IOV)” section in the User Manual.Keywords: Installation/Upgrade-Description: On machines configured with NVGRE encapsulation with the encapsulation taskoffload enabled, incoming VXLAN traffic on the interface may be reported with wrong check-sum status.Workaround : N/AKeywords: Virtualization-Description: Running Ntttcp without the “-a X” flag (X >1) in a NIC configured with10GbE may cause low bandwidth in TCP single streamWorkaround : Run Ntttcp with “-a 8” for best performanceKeywords: Performance-Description: RDMA read on single QP 100GbE RoCE cannot achieve more than 50Gb/s.Workaround :•Use more than one QP•Use Jumbo packets (4K)Keywords: Performance576556Description: “TCP RSC Average Packet Size” counter under network adapter does not countcorrectly. This is a known operating system issue.Workaround : N/AKeywords: GeneralWorkaroundTable 1 - Archived Known Issues (Sheet 3 of 5)Internal Ref.IssueRev 1.08Mellanox Technologies 683840Description: In Windows Server 2016, the following RDMA counters for VPorts that werecreated to use RDMA capability will show statistics for all the VPorts connected to the sameinterface and not for a specific VPort:•RDMA Inbound Bytes/sec•RDMA Inbound Frames/sec•RDMA Outbound Bytes/sec•RDMA Outbound Frames/secWorkaround : N/AKeywords: RDMA786035Description: Running applications on top of MS MPI may result in failure.Workaround : N/AKeywords: RDMA877750Description: Occasionally, the adapter card shows an error of duplicate IPv4 address whendisabling and enabling the adapter through Device Manager.Workaround : Reboot the machine instead of disabling and enabling it in the Device Manager.Keywords: Device Manager, IPv4825154Description: Mellanox WinOF-2 Device Diagnostic and PCI Device Diagnostic countersreported in PerfMon are per device. The counters that are reported per adapter under these setsshow the counters for all the devices and not only for the specific adapter.Workaround : N/AKeywords: perfmon, counters894614Description: The nd_*_bw and nd_*_lat tools do not work on Windows server 2012, Win-dows 8.1 and Windows Server 2012 R2. An error message appears, notifying that the api-ms-win-crt.dll is missing.Workaround : Windows update kb2999226 must be downloaded and installed, in order toobtain the universal c run time dlls. To download the update, go to https://support.micro-/en-us/kb/2999226.To verify that the update is installed, run the following powershell command:get-hotfix -id kb2999226Keywords: nd tools, Windows 2012, Windows 2012 R, missing dll, Universal C Runtime899853Description: Uninstallation of the driver does not reset all network adapter configurations tothe default values.Workaround : Upon completion of the uninstallation process, run the following powershellcommand for each network adapter, while replacing <AdapterName> with the name of the rel-evant network adapter:Reset-NetAdapterAdvancedProperty -Name "<AdapterName>" -DisplayName"*"Keywords: Uninstallation, network adapter configurations, Windows Server 2016, Windows10Table 1 - Archived Known Issues (Sheet 4 of 5)Internal Ref.IssueArchived Known Issues Rev 1.09Mellanox Technologies 778631Description: IB utils are currently not a part of the WinOF-2 packageWorkaround : Fabric diagnostic can be done from a managed switch or a different node in the fabric with IB utils support.Keywords: InfiniBand, IB utils, fabric diagnosticTable 1 - Archived Known Issues (Sheet 5 of 5)Internal Ref.Issue。
包含了《Winsock2h》,创建SOCKET时出错。引起出错的语
一,创建一个win32,应用程序(Win32 Application),包含了<Winsock2.h>,创建SOCKET 时出错。
引起出错的语句:SOCKET myUDPSock = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP),问题现象:编译可以通过,连接时有如下错误,超找帮助发现可能执行函数时,没有连接到库,在Projects->settings link中加入ws2_32.lib链接,问题解决。
(2010-8-8)--------------------Configuration: WINMAIN3 - Win32 Debug--------------------Linking...WINMAIN3.obj : error LNK2001: unresolved external symbol __imp__socket@12Debug/WINMAIN3.exe : fatal error LNK1120: 1 unresolved externalsError executing link.exe.WINMAIN3.exe - 2 error(s), 0 warning(s)二、出现预编译文件找不到,问题原因可能是一个工作区包含了多个工程,第一个工程编译编译运行后,就会在工程设置里增加预编译头文件,新建的工程继承了原来工程的设置,所以在运行时会找原来的文件而找不到。
解决方法:更改工程设置,去掉这个预编译头文件如图:2010-8-14三、free和malloc的使用注意事项在一次编程中出现下面的断言错误,经过反复试验,发现是free的指针所指的内存不是malloc分配的,而是一个数组在定义时分配的。
结合msdn对free和malloc的解释:The free function deallocates a memory block (memblock) that was previously allocated by a call to calloc, malloc, or realloc. The number of freed bytes is equivalent to the number of bytes requested when the block was allocated (or reallocated, in the case of realloc). If memblock is NULL, the pointer is ignored and free immediately returns. Attempting to free an invalid pointer (a pointer to a memory block that was not allocated by calloc, malloc, or realloc) may affect subsequent allocation requests and cause errors.After a memory block has been freed, _heapmin minimizes the amount of free memory on the heap by coalescing the unused regions and releasing them back to the operating system. Freed memory that is not released to the operating system is restored to the free pool and is available for allocation again.可以看出malloc分配的内存是从heap(堆)中获得的,free函数也就只能free堆里的内存,因此,当调用函数去free一快栈里的内存是,就会有下面的错误。
winsock2
来源Windows8论坛:winsock2WinSock2就相当于连接系统和你使用的软件之间交流的一个接口,可能这个功能就是修复软件与系统正确的通讯的作用。
Winsock2 SPI(Service Provider Interface)服务提供者接口建立在Windows 开放系统架构WOSA(Windows Open System Architecture)之上,是Winsock系统组件提供的面向系统底层的编程接口。
Winsock系统组件向上面向用户应用程序提供一个标准的API接口;向下在Winsock组件和Winsock服务提供者(比如TCP /IP协议栈)之间提供一个标准的SPI接口。
各种服务提供者是Windows支持的DL L,挂靠在Winsock2 的Ws2_32.dll模块下。
对用户应用程序使用的Winsock2 API 中定义的许多内部函数来说,这些服务提供者都提供了它们的对应的运作方式(例如A PI函数WSAConnect有相应的SPI函数WSPConnect)。
多数情况下,一个应用程序在调用Winsock2 API函数时,Ws2_32.dll会调用相应的Winsock2 SPI函数,利用特定的服务提供者执行所请求的服务。
Winsock2 SPI允许开发两类服务提供者——传输服务提供者和名字空间服务提供者。
“传输提供者”(Transport Providers, 一般称作协议堆栈,例如TCP/IP)能够提供建立通信、传输数据、日常数据流控制和错误控制等传输功能方面的服务。
“名字空间提供者”(Name Space Providers,例如DNS名字解析服务)则把一个网络协议的地址属性和一个或多个用户友好名称关联到一起,以便启用与应用无关的名字解析方案。
Winsock2中使用的传输服务提供者有两类:基础服务提供者和分层服务提供者。
基础服务提供者执行网络传输协议(比如TCP/IP)的具体细节,其中包括在网络上收发数据之类的核心网络协议功能。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
WINSOCK 2WINDOWS SOCKET: PROGRAM EXAMPLESPART 8Machine’s OS is standalone Windows Xp Pro with SP2 except whenevermentioned. Compiler used was Visual C++ 2003 .Net 1.1. Beware the codes thatspan more than one line. Program examples have been tested for NonDestructive Test. All information compiled for Windows 2000 (NT5.0) aboveand...1.The story was discussed at Winsock introduction story.2.Related functions, structures and macros used in the program exampleshave been dumped at Winsock structure & function 1 and Winsockstructure & function 2.3.Other related and required information (if any) not available in no. 2 canbe found at MSDN & Visual C++ online reference.AbilitiesAble to understand more Winsock implementation and operations through the APIs and program examples.Able to gather, understand and use the Winsock functions,structures and macros in your programs.Able to build programs that use Microsoft C/Standard C programminglanguage and Winsock APIs.sockaddrItem DescriptionStructure sockaddr.Info Contains socket address information. The sockaddr structure varies depending on the protocol selected. It is better to use SOCKADDR_STORAGE instead.Definition struct sockaddr_in {short sin_family;u_short sin_port;struct in_addr sin_addr; char sin_zero[8];};struct sockaddr_in6 {short sin6_family;u_short sin6_port;u_long sin6_flowinfo;struct in6_addr sin6_addr; u_long sin6_scope_id; };struct sockaddr_in6_old {short sin6_family;u_short sin6_port;u_long sin6_flowinfo;struct in6_addr sin6_addr;};Members As mentioned above.Header file<winsock2.h> for IPv4; <ws2tcpip.h> for IPv6.RemarkThe sockaddr structure varies depending on the protocol selected. Except for thesin*_family parameter, sockaddr contents are expressed in network byte order.Winsock functions using sockaddr are not strictly interpreted to be pointers to a sockaddr structure. The structure is interpreted differently in the context of different address families. The only requirements are that the first u_short is the address family and the total size of the memory buffer in bytes is namelen. Other protocols use similar structures.Table 1Program ExampleThe following example demonstrates the use of the sockaddr structure.#include <stdio.h>#include "winsock2.h"int main(){// Declare variablesWSADATA wsaData;SOCKET ListenSocket;sockaddr_in service;// Initialize Winsock, request the Winsock 2.2int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);if(iResult != NO_ERROR)printf("Error at WSAStartup().\n");elseprintf("WSAStartup() is OK.\n");// Create a listening socketListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);if (ListenSocket == INVALID_SOCKET){printf("Error at socket().\n");WSACleanup();return 0;}elseprintf("socket() is OK.\n");// Bind the socket to the local IP address and port 55555hostent* thisHost;char* ip;u_short port;port = 55555;thisHost = gethostbyname("");ip = inet_ntoa(*(struct in_addr *)*thisHost->h_addr_list);printf("\nIP address is: %s.\n", ip);printf("Hostname is: %s.\n", thisHost->h_name);printf("Address type: %i.\n\n", thisHost->h_addrtype);service.sin_family = AF_INET;service.sin_addr.s_addr = inet_addr(ip);service.sin_port = htons(port);if (bind(ListenSocket,(SOCKADDR*) &service, sizeof(service)) ==SOCKET_ERROR){printf("bind() failed lol!\n");closesocket(ListenSocket);return 0;}elseprintf("bind() is OK.\n");WSACleanup();return 0;}Figure 1hostentem Descriptioncture hostentUsed by functions to store information about a given host, such as host name, IP address, and so forth. An application should never attempt to modify this structure or to free any of its components. Furthermore, only copy of the hostent structure is allocated per thread, and an application should therefore copy any informatiothat it needs before issuing any other Windows Sockets API calls.nition typedef struct hostent {char FAR* h_name;char FAR FAR** h_aliases; short h_addrtype;short h_length;char FAR FAR** h_addr_list; } hostent;mbers h_name - Official name of the host (PC). If using the DNS or similar resolution system, it is the Fully Qualified Domain Name (FQDN) that caused the server to return a reply. If using a local hosts file, it is the first entry a the IP address.h_aliases - Null-terminated array of alternate names.h_addrtype - Type of address being returned.h_length - Length of each address, in bytes.h_addr_list - Null-terminated list of addresses for the host. Addresses are returned in network byte order. Th macro h_addr is defined to be h_addr_list[0] for compatibility with older software.der<winsock2.h>mark-Table 2gethostbyaddr()Item Descriptionction gethostbyaddr()Retrieves the host information corresponding to a network address. The gethostbyaddr function hasbeen deprecated by the introduction of the getnameinfo() function. Developers creating WindowsSockets 2 applications are urged to use the getnameinfo() function instead of the gethostbyaddr()function.otype struct HOSTENT* FAR gethostbyaddr( const char* addr, int len, int type);ameters addr - [in] Pointer to an address in network byte order.len - [in] Length of the address, in bytes.type - [in] Type of the address, such as the AF_INET address family type (defined as TCP, UDP, and other associated Internet protocols). Address family types and their corresponding values are defined the winsock2.h header file.urn value See below. ude file<winsock2.h> ary ws2_32.lib.mark The gethostbyaddr() function returns a pointer to the hostent structure that contains the name and address corresponding to the given network address. Although gethostbyaddr is deprecated by the getnameinfo() function, gethostbyaddr is capable of returning a NetBIOS name; getnameinfo is not. Developers requiring NetBIOS name resolution may need to use gethostbyaddr() until their applicatio are completely independent of NetBIOS names. Note The capability to perform reverse lookups usin the gethostbyaddr function is convenient, but such lookups are considered inherently unreliable, and should be used only as a hint.Table 3Return ValuesIf no error occurs, gethostbyaddr() returns a pointer to the hostent structure. Otherwise, it returns a null pointer, and a specific error code can be retrieved by calling WSAGetLastError().Error code MeaningWSANOTINITIALISED A successful WSAStartup() call must occur before using this function.WSAENETDOWN The network subsystem has failed. WSAHOST_NOT_FOUND Authoritative answer host not found.WSATRY_AGAIN Non-authoritative host not found, or server failed.WSANO_RECOVERY A non-recoverable error occurred.WSANO_DATA Valid name, no data record of requested type.WSAEINPROGRESS A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.WSAEAFNOSUPPORT The type specified is not supported by the Windows Sockets implementation.WSAEFAULT The addr parameter is not a valid part of the user address space, or the len parameter is too small.WSAEINTR A blocking Windows Socket 1.1 call was canceled through WSACancelBlockingCall().Table 4For program sample, see the following example.gethostbyname()Item Description nction gethostbyname().e Retrieves host information corresponding to a host name from a host database. The gethostbyname( function has been deprecated by the introduction of the getaddrinfo() function. Developers creating Windows Sockets 2 applications are urged to use the getaddrinfo() function instead of gethostbynamtotype struct hostent* FAR gethostbyname(const char* name);ameters name - [in] Pointer to the null-terminated name of the host to resolve. urn value See below.ude file<winsock2.h>rary ws2_32.lib.mark The gethostbyname() function returns a pointer to a hostent structure - a structure allocated by Windows Sockets. The hostent structure contains the results of a successful search for the host specified in the name parameter.The application must never attempt to modify this structure or to free any of its components. Furthermore, only one copy of this structure is allocated per thread, so the application should copy an information it needs before issuing any other Windows Sockets function calls.The gethostbyname() function cannot resolve IP address strings passed to it. Such a request is treate exactly as if an unknown host name were passed. Use inet_addr to convert an IP address string the string to an actual IP address, then use another function, gethostbyaddr(), to obtain the contents of th hostent structure. If null is provided in the name parameter, the returned string is the same as the stri returned by a successful gethostname() function call. The gethostbyname() function does not check t size of the name parameter before passing the buffer. In improperly sized name parameters, heap corruption can occur.Table 5Return ValuesIf no error occurs, gethostbyname() returns a pointer to the hostent structuredescribed above. Otherwise, it returns a null pointer and a specific error numbercan be retrieved by calling WSAGetLastError().Error code MeaningWSANOTINITIALISEDA successful WSAStartup() call mustoccur before using this function.WSAENETDOWN The network subsystem has failed.WSAHOST_NOT_FOUND Authoritative answer host not found.WSATRY_AGAINNon-authoritative host not found, orserver failure.WSANO_RECOVERY A non-recoverable error occurred.WSANO_DATAValid name, no data record ofrequested type.WSAEINPROGRESSA blocking Windows Sockets 1.1 call isin progress, or the service provider isstill processing a callback function.WSAEFAULTThe name parameter is not a valid partof the user address space.WSAEINTRA blocking Windows Socket 1.1 callwas canceled throughWSACancelBlockingCall().Table 6Program ExampleThe following examples demonstrates the use of the gethostbyname() and gethostbyaddr() functions.#include <stdio.h>#include <winsock2.h>int main(){// Declare variablesWSADATA wsaData;// Initialize Winsock, request the Winsock 2.2int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);if(iResult != NO_ERROR)printf("Error at WSAStartup().\n");elseprintf("WSAStartup() is OK.\n");// Declare and initialize variableshostent* remoteHost;char* ip;char* host_name;unsigned int addr;// User inputs name of hostprintf("Input name/IP of host: ");host_name = (char*) malloc(sizeof(char*)*128);fgets(host_name, 128, stdin);// If the user input is an alpha name for the host, use gethostbyname()// else, gethostbyaddr() (assume IPv4)// host address is a nameif (isalpha(host_name[0])){printf("\nUsing gethostbyname()...\n");// NULL terminatedhost_name[strlen(host_name)-1] = '\0';remoteHost = gethostbyname(host_name);ip = inet_ntoa(*(struct in_addr *)*remoteHost->h_addr_list);printf("IP address is: %s.\n", ip);printf("Address type: %i.\n\n", remoteHost->h_addrtype);}else{printf("\nUsing gethostbyaddr()...\n");addr = inet_addr(host_name);remoteHost = gethostbyaddr((char *)&addr, 4, AF_INET);printf("Hostname is: %s.\n", remoteHost->h_name);printf("Address type: %i.\n\n", remoteHost->h_addrtype); }if (WSAGetLastError() != 0){if (WSAGetLastError() == 11001)printf("Host not found...\nExiting.\n");}elseprintf("error #: %ld\n", WSAGetLastError());// The remoteHost structure can now be used to// access information about the hostWSACleanup();return 0;}Figure 2Figure 3。