A New Way to Ping

Environment: VC6, WIN32

   On several occasions I’ve needed to use the functionality of the TCP ping utility programmatically. On one occasion I actually needed to get the hops count. I know there are numerous examples of using the ICMP interface but Microsoft has stated this interface is subject to change. It’s also complicated to understand and program.

In searching the SDK I found the iphlpapi function GetRTTAndHopCount. This was just what I needed, one system function that does what I want. It also doesn’t use any of the arcane sockets structures. The SDK documentation gives this description:

BOOL GetRTTAndHopCount(
  IPAddr DestIpAddress,  // destination IP address 
  PULONG HopCount,       // returned hop count
  ULONG MaxHops,         // limit on number of hops to search
  PULONG RTT             // round-trip time
);

Like a lot of the Win32 functions, if the function returns false you call GetLastError() for the specific error, typically a Winsock error. I find that the error returned when a host fails to respond is 11010, which the winsock2.h file describes as WSA_QOS_ADMISSION_FAILURE. This is not very informative (and maybe wrong). I think using the Boolean return is sufficient (they replied or they didn’t).

The following is an example of how to use this new function.

#include <iphlpapi.h>
//-----------------------------------------------------------------
void CNewPingDlg::OnPingbutton()
{
int rc;
IPAddr ia;

    UpdateData(TRUE);
    ia = inet_addr (m_ip_address);
    rc = NewPing(ia, (ULONG*)&m_hops_count,(ULONG*)&m_rtt);
    if (rc == 0)
        m_status = "Get RTTL and Hops Succeeded";
    else
        m_status.Format("Host not responding or no route, rc = %d",rc);
    UpdateData(FALSE);
    MessageBeep(1000);
    return;
}
//-------------------------------------------------------------
int NewPing(IPAddr ia, ULONG *hops_count, ULONG *rtt)
{
boolean IsOk;

  IsOk = GetRTTAndHopCount(ia, hops_count,128, rtt); //the iphlpapi call
  if (IsOk == TRUE)	return 0;
  return GetLastError();
}
//---------------------------------------------------------------

    That’s it. The only thing I did was hide and hard code the maximum hops to search in this function. More than 128 hops is a long way off, if ever. This function could be easily be put into a separate thread to make an asynchronous version.

Downloads

Download demo project – 28 Kb

Download source – 4 Kb

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read