WinCE 下实现 ping 功能


需要包括的头文件与库文件:

#include "Winsock2.h"
// PING
#include "Ipexport.h"
#include "Icmpapi.h"
#include "winsock.h"

extern HWND ghMainWnd;

#pragma comment (lib, "Iphlpapi.lib") 
#pragma comment (lib, "Ws2.lib") 


源代码如下:

int Ping(TCHAR *Address , int iTtl , int iWaitTime , TCHAR *szName , int *prtt)
{
	IPAddr                ipAddress ;
	IP_OPTION_INFORMATION ipInfo ;
	ICMP_ECHO_REPLY       icmpEcho;	
	HANDLE                hFile;	
	char                  strHost  [ MAX_PATH ] ;
	TCHAR                 szPCName [ MAX_PATH ]  = { TEXT( "" ) } ;
	int                   iRet = -1 ;
	struct in_addr iaDest;		// Internet address structure
	LPHOSTENT pHost;			// Pointer to host entry structure

	RETAILMSG(1,(L"TICK: %d - [TCP Client]Enter Ping......\r\n",GetTickCount() / 1000));

	_tcscpy( szName , TEXT("") );
	WideCharToMultiByte( CP_ACP, 0, Address , -1, strHost, sizeof( strHost ), NULL, FALSE );
	ipAddress = inet_addr(strHost);
	iaDest.s_addr = inet_addr(strHost);
	if (iaDest.s_addr == INADDR_NONE)
	{
		pHost = gethostbyname(strHost);
		if( pHost )
		{
			char *pIP ;
			iaDest.S_un.S_addr = *(DWORD *)(*pHost->h_addr_list) ;
			pIP = inet_ntoa( iaDest ) ;
			if( strlen( pIP ) )
				MultiByteToWideChar( CP_ACP, 0, pIP , -1, szPCName, sizeof( szPCName ) );
			if( _tcslen( szPCName ) )
				_tcscpy( szName , szPCName );
		}
	}
	else
	{
		pHost = gethostbyaddr((const char *)&iaDest, 
			sizeof(struct in_addr), AF_INET);
		if( pHost )
		{
			MultiByteToWideChar( CP_ACP, 0, pHost->h_name , -1, szPCName, sizeof( szPCName ) );
			if( _tcslen( szPCName ) )
				_tcscpy( szName , szPCName );
		}
	}
	if( pHost )
		ipAddress = *(DWORD *)(*pHost->h_addr_list) ;
	if (ipAddress != INADDR_NONE)
	{	
		iRet = 0 ;
		hFile = IcmpCreateFile();

		// Set some reasonable default values
		ipInfo.Ttl   = iTtl ;
		ipInfo.Tos   = 0;
		ipInfo.Flags = 0;
		ipInfo.OptionsSize = 0 ;
		ipInfo.OptionsData = NULL ;
		icmpEcho.Status    = IP_REQ_TIMED_OUT/*IP_SUCCESS*/ ;
		IcmpSendEcho( hFile , ipAddress , NULL , 0 ,
			(PIP_OPTION_INFORMATION)&ipInfo,
			&icmpEcho , sizeof(ICMP_ECHO_REPLY) , iWaitTime ) ;	
		IcmpCloseHandle(hFile) ;
		if ( icmpEcho.Status == IP_SUCCESS )
			iRet = 1 ;

		*prtt = icmpEcho.RoundTripTime ;
	}
	return iRet ;
}


调用示例:

static LPTSTR strIpAddr[] = 
{
	L"202.96.209.5",		// 上海 DNS
	L"220.181.6.18",		// 百度
	L"202.100.4.15",		// 西安 DNS
};
TCHAR tcName[MAX_PATH] = {0};
int iPtt = 0;
int iPingRet = Ping(strIpAddr[giPingIndex],128,3000,tcName,&iPtt);	//ping tmc server

if(iPingRet == 1)
{
	RETAILMSG(1, (TEXT("TICK: %d - Ping IP: %s Success.\r\n"),GetTickCount() / 1000, strIpAddr[giPingIndex]));
}
else
{
	// 失败
}



你可能感兴趣的:(WinCE 下实现 ping 功能)