WinCE 下实现 ping 功能
需要包括的头文件与库文件:
1 #include "Winsock2.h" 2 // PING 3 #include "Ipexport.h" 4 #include "Icmpapi.h" 5 #include "winsock.h" 6 7 extern HWND ghMainWnd; 8 9 #pragma comment (lib, "Iphlpapi.lib") 10 #pragma comment (lib, "Ws2.lib")
源代码如下:
1 int Ping(TCHAR *Address , int iTtl , int iWaitTime , TCHAR *szName , int *prtt) 2 { 3 IPAddr ipAddress ; 4 IP_OPTION_INFORMATION ipInfo ; 5 ICMP_ECHO_REPLY icmpEcho; 6 HANDLE hFile; 7 char strHost [ MAX_PATH ] ; 8 TCHAR szPCName [ MAX_PATH ] = { TEXT( "" ) } ; 9 int iRet = -1 ; 10 struct in_addr iaDest; // Internet address structure 11 LPHOSTENT pHost; // Pointer to host entry structure 12 13 RETAILMSG(1,(L"TICK: %d - [TCP Client]Enter Ping......\r\n",GetTickCount() / 1000)); 14 15 _tcscpy( szName , TEXT("") ); 16 WideCharToMultiByte( CP_ACP, 0, Address , -1, strHost, sizeof( strHost ), NULL, FALSE ); 17 ipAddress = inet_addr(strHost); 18 iaDest.s_addr = inet_addr(strHost); 19 if (iaDest.s_addr == INADDR_NONE) 20 { 21 pHost = gethostbyname(strHost); 22 if( pHost ) 23 { 24 char *pIP ; 25 iaDest.S_un.S_addr = *(DWORD *)(*pHost->h_addr_list) ; 26 pIP = inet_ntoa( iaDest ) ; 27 if( strlen( pIP ) ) 28 MultiByteToWideChar( CP_ACP, 0, pIP , -1, szPCName, sizeof( szPCName ) ); 29 if( _tcslen( szPCName ) ) 30 _tcscpy( szName , szPCName ); 31 } 32 } 33 else 34 { 35 pHost = gethostbyaddr((const char *)&iaDest, 36 sizeof(struct in_addr), AF_INET); 37 if( pHost ) 38 { 39 MultiByteToWideChar( CP_ACP, 0, pHost->h_name , -1, szPCName, sizeof( szPCName ) ); 40 if( _tcslen( szPCName ) ) 41 _tcscpy( szName , szPCName ); 42 } 43 } 44 if( pHost ) 45 ipAddress = *(DWORD *)(*pHost->h_addr_list) ; 46 if (ipAddress != INADDR_NONE) 47 { 48 iRet = 0 ; 49 hFile = IcmpCreateFile(); 50 51 // Set some reasonable default values 52 ipInfo.Ttl = iTtl ; 53 ipInfo.Tos = 0; 54 ipInfo.Flags = 0; 55 ipInfo.OptionsSize = 0 ; 56 ipInfo.OptionsData = NULL ; 57 icmpEcho.Status = IP_REQ_TIMED_OUT/*IP_SUCCESS*/ ; 58 IcmpSendEcho( hFile , ipAddress , NULL , 0 , 59 (PIP_OPTION_INFORMATION)&ipInfo, 60 &icmpEcho , sizeof(ICMP_ECHO_REPLY) , iWaitTime ) ; 61 IcmpCloseHandle(hFile) ; 62 if ( icmpEcho.Status == IP_SUCCESS ) 63 iRet = 1 ; 64 65 *prtt = icmpEcho.RoundTripTime ; 66 } 67 return iRet ; 68 }
调用示例:
1 static LPTSTR strIpAddr[] = 2 { 3 L"202.96.209.5", // 上海 DNS 4 L"220.181.6.18", // 百度 5 L"202.100.4.15", // 西安 DNS 6 }; 7 8 TCHAR tcName[MAX_PATH] = {0}; 9 int iPtt = 0; 10 int iPingRet = Ping(strIpAddr[giPingIndex],128,3000,tcName,&iPtt); //ping tmc server 11 12 if(iPingRet == 1) 13 { 14 RETAILMSG(1, (TEXT("TICK: %d - Ping IP: %s Success.\r\n"),GetTickCount() / 1000, strIpAddr[giPingIndex])); 15 } 16 else 17 { 18 }