Knowledge Base Nr: 00033 ping.cpp - http://www.swe-kaiser.de

Win32: 'ping'en von name oder ip-nummer mit timeout
achtung: icmp.lib, ipexport.h, icmpapi.h von microsoft müssen aus dem internet nachgeladen werden!

  
#include <stdafx.h>
#include <ras.h>
#include <winsock.h>

#pragma comment(lib, "C:/Program Files/Microsoft Visual Studio/VC98/Lib/RASAPI32.LIB")

extern "C" {
#include "icmp\ipexport.h"
#include "icmp\icmpapi.h"
}

#pragma comment(lib, "/projects/msvc60/cpp_classes/icmp/icmp.lib")

int Ping(const char* szHostAddr, int nTimeOut)
{
IPAddr ip;

hostent* phostent;
if( szHostAddr[0] <= '9')
ip = (IPAddr)inet_addr(szHostAddr);
else
{
phostent = gethostbyname(szHostAddr); //may take serveral seconds!
if (!phostent)
return -1;

ip = *(DWORD*)(*phostent->h_addr_list);
}

HANDLE icmphandle = IcmpCreateFile();
if (!icmphandle)
return -2;

char reply[sizeof(icmp_echo_reply)+8];

icmp_echo_reply* iep = (icmp_echo_reply*)&reply;
iep->RoundTripTime = 0xffffffff;

IcmpSendEcho(icmphandle,ip,0,0,NULL,reply,sizeof(icmp_echo_reply)+8, nTimeOut);
int nErr = ::GetLastError();

IcmpCloseHandle(icmphandle);

return nErr ? -3 : iep->RoundTripTime;
}