Library tutorials & articles
How to PING
- Introduction
- The Class
- Wrapping Up
The Class
Now let's get down and dirty and write some code. First off, I have no idea how to send ICMP packets with the socket library. I'll leave that for the pros. My sample code will use a little known ICMP. DLL found in the System32 folder. This DLL exports eight functions. I'll limit our discussion to the three important ones.
HANDLE WINAPI IcmpCreateFile (VOID);
BOOL WINAPI IcmpCloseHandle (HANDLE IcmpHandle);
DWORD WINAPI IcmpSendEcho (HANDLE IcmpHandle,
IPAddr DestinationAddress, LPVOID RequestData,
WORD RequestSize, PIP_OPTION_INFORMATION RequestOptions,
LPVOID ReplyBuffer, DWORD ReplySize, DWORD Timeout);
The IcmpCreateFile function returns a handle that is used to execute ICMP requests. The IcmpCloseHandle function closes the handle created by IcmpCreateFile. The last function is IcmpSendEcho. This function given a handle will send one ICMP packet to a host and wait a specified timeout period or until a reply is received.
HANDLE icmphandle = IcmpCreateFile();
char reply[sizeof(icmp_echo_reply)+8];
icmp_echo_reply* iep = (icmp_echo_reply*)&reply;
iep->RoundTripTime = 0xffffffff;
DWORD dw = IcmpSendEcho(icmphandle,
*((u_long*) host->h_addr_list[0]),
0,0, NULL,
reply, sizeof(icmp_echo_reply)+8,5000);
if (dw == 0)
{
throw IcmpException("send echo failed");
}
IcmpCloseHandle(icmphandle);
The code for sending one ICMP packet with zero content is very minimal. Create the handle, setup the reply buffer, call the IcmpSendEcho method, test for error conditions and close the handle. The only part that is left is to figure out how to construct the *((u_long*) host-> h_addr_list[0]) or host address.
hostent * host;
in_addr inaddr;
inaddr.s_addr = ::inet_addr(strAddress.c_str());
if (inaddr.s_addr == INADDR_NONE)
{
host = ::gethostbyname(strAddress.c_str());
}
else
{
host = ::gethostbyaddr((const char *)&inaddr,
sizeof(inaddr), AF_INET);
}
if (host == NULL)
{
throw IcmpException("invalid SMTP server");
}
In this code sample, I determine if the address is an IP address or a name that should be resolved to an IP address. Then I construct the host structure from the name or address.
Related articles
Related discussion
-
Convert C++ code to VB6
by mawcot (4 replies)
-
How to create a games like FIFA08
by mawcot (0 replies)
-
Binary Studio | software development outsourcing Ukraine
by shane124 (4 replies)
-
Seeking developers for Montreal Office
by mazen_kt (1 replies)
-
Is there anyone here willing to be interviewed regarding their career in IT?
by krizs (1 replies)
hfhg
What is the name of library to include ?
include ???
In the icmp.h and ping.cpp
Thanks
i need to develop a ping plotter + a route tracer in c # but the problem is i am a newbie and dont know much so how do i go about this or if any source code is available for pining in c # would be grateful
This thread is for discussions of How to PING.