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.
Comments