windows C++通过Ping查看某个IP是否在线
注:以下代码从网上某位大神处摘抄下来,此处仅做记录使用,不做它用
原大神文章链接:C++验证IP是否可以PING通 - 梦雨轩 - 博客园 (cnblogs.com)
1 #include <WinSock2.h> 2 #include <iphlpapi.h> 3 #include <iostream> 4 5 #pragma comment(lib,"Iphlpapi.lib") 6 #pragma comment(lib,"Ws2_32.lib") 7 typedef HANDLE(WINAPI* ICMPCREATEFILE)(VOID); 8 typedef INT(WINAPI* ICMPCLOSEHANDLE)(HANDLE); 9 typedef DWORD(WINAPI* ICMPSENDECHO)(HANDLE, DWORD, LPVOID, WORD, PIP_OPTION_INFORMATION, LPVOID, DWORD, DWORD); 10 11 //定义三个指针函数 12 ICMPCREATEFILE pIcmpCreateFile; 13 ICMPCLOSEHANDLE pIcmpCloseHandle; 14 ICMPSENDECHO pIcmpSendEcho; 15 // 函数功能:初始化ICMP函数: 16 BOOL InitIcmp() 17 { 18 HINSTANCE hIcmp = LoadLibrary(L"ICMP.DLL"); 19 if (hIcmp == NULL) 20 { 21 return false; 22 } 23 pIcmpCreateFile = (ICMPCREATEFILE)GetProcAddress(hIcmp, "IcmpCreateFile"); 24 pIcmpCloseHandle = (ICMPCLOSEHANDLE)GetProcAddress(hIcmp, "IcmpCloseHandle"); 25 pIcmpSendEcho = (ICMPSENDECHO)GetProcAddress(hIcmp, "IcmpSendEcho"); 26 if ((pIcmpCreateFile == NULL) || (pIcmpCloseHandle == NULL) || (pIcmpSendEcho == NULL)) 27 return false; 28 return true; 29 } 30 31 // 函数功能:判断是否能ping通IP 32 // 函数参数:IP地址或域名 33 INT ICMPPing(char* host) 34 { 35 DWORD timeOut = 1000; //设置超时 36 ULONG hAddr = inet_addr(host); //如果是IP地址就直接转换 37 if (hAddr == INADDR_NONE) 38 { 39 hostent* hp = gethostbyname(host); //如果是域名就用DNS解析出IP地址 40 if (hp) 41 memcpy(&hAddr, hp->h_addr_list, hp->h_length); //IP地址 42 else 43 { 44 return 0; 45 } 46 } 47 HANDLE hIp = pIcmpCreateFile(); 48 IP_OPTION_INFORMATION ipoi; 49 memset(&ipoi, 0, sizeof(IP_OPTION_INFORMATION)); 50 ipoi.Ttl = 128; //Time-To-Live 51 52 unsigned char pSend[36]; //发送包 53 memset(pSend, 'E', 32); 54 55 int repSize = sizeof(ICMP_ECHO_REPLY) + 32; 56 unsigned char pReply[100]; //接收包 57 ICMP_ECHO_REPLY* pEchoReply = (ICMP_ECHO_REPLY*)pReply; 58 59 DWORD nPackets = pIcmpSendEcho(hIp, hAddr, pSend, 32, &ipoi, pReply, repSize, timeOut); //发送ICMP数据报文 60 61 if (pEchoReply->Status != 0) //超时,可能是主机禁用了ICMP 或者目标主机不存在 62 { 63 pIcmpCloseHandle(hIp); 64 return 0; 65 } 66 67 pIcmpCloseHandle(hIp); 68 return 1; 69 } 70 int main() 71 { 72 InitIcmp(); 73 74 int ping2C = ICMPPing("10.192.168.1"); 75 std::string stDevInfo = "1234"; 76 for (int i = 0; i < 4; i++) 77 { 78 79 //char cPwd[2] = {0}; 80 //cPwd[0] = stDevInfo[i]; 81 char cPwd = stDevInfo[i]; 82 83 std::cout << "cPwd = " << &cPwd << std::endl; 84 int nT = (char)strtol(&cPwd, NULL, 16); 85 std::cout << "nT =" << nT << std::endl; 86 87 } 88 89 system("pause"); 90 return 0; 91 }