您的位置:首页 > 其它

WinCE 下实现 ping 功能

2014-02-21 11:23 260 查看
需要包括的头文件与库文件:

#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
{
// 失败
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: