在C++中實現ping功能,並不難。但真正了解ping是需要花費一番功夫的。
Ping功能是在ICMP基礎上實現的。IP協議並不是一個可靠的協議,它不保證數據被送達,那么,保證數據送達的工作應該由其他的模塊來完成。其中一個重要的模塊就是ICMP(網絡控制報文)協議。ICMP主要是用來實現IP系統間傳遞差錯和管理報文,是任何IP實現必須和要求的組成部分。它是TCP/IP協議族的一個子協議,屬於網絡層協議。ICMP提供一致易懂的出錯報告信息。發送的出錯報文返回到發送原數據的設備,因為只有發送設備才是出錯報文的邏輯接受者。發送設備隨后可根據ICMP報文確定發生錯誤的類型,並確定如何才能更好地重發失敗的數據包。當傳送IP數據包發生錯誤--比如主機不可達,路由不可達等等,ICMP協議將會把錯誤信息封包,然后傳送回給主機。給主機一個處理錯誤的機會,這也就是為什么說建立在IP層以上的協議是可能做到安全的原因。
。在程序中實現Ping功能時,常用的方法有三:
一、調用system實現
#include <windows.h>
#include <stdio.h>
#include <string.h>
char YN(int k) {
FILE *f;
char fn[40];
char ln[80];
char yn;
int n;
yn='N';
sprintf(fn,"d:\\ping%d.txt",k);
f=fopen(fn,"r");
if (NULL!=f) {
n=0;
while (1) {
if (NULL==fgets(ln,80,f)) break;//
if (strstr(ln,"ms ")) {
yn='Y';
break;//
}
n++;
if (n>=4) break;//
}
fclose(f);
}
return yn;
}
void main(int argc,char **argv) {
char cmdstr[256];
int i;
int IP[3];
char c;
if (argc<2) {
USAGE:
printf("Usage example:\n %s 192.168.60.\nto test 192.168.60.1-254\n",argv[0]);
return;
}
if (4==sscanf(argv[1],"%d.%d.%d%c",&IP[0],&IP[1],&IP[2],&c)) {
if (0<=IP[0] && IP[0]<=255
&& 0<=IP[1] && IP[1]<=255
&& 0<=IP[2] && IP[2]<=255
&& '.'==c) {
for (i=1;i<255;i++) {
sprintf(cmdstr,"cmd /c ping %s%d -n 1 -w 1000 >d:\\ping%d.txt",argv[1],i,i);
WinExec(cmdstr,SW_HIDE);
}
Sleep(3000);
for (i=1;i<255;i++) {
printf("%c %s%d\n",YN(i),argv[1],i);
}
Sleep(3000);
WinExec("cmd /c del /q d:\\ping*.txt",SW_HIDE);
} else goto USAGE;
} else goto USAGE;
}
二、使用socket協議實現
// MyPing.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <winsock2.h>
#include <WS2tcpip.h>
#include <stdio.h>
#include <stdlib.h>
#define ICMP_ECHO 8
#define ICMP_ECHOREPLY 0
#define ICMP_MIN 8 //Minimum 8-byte ICMP packet (header)
#define DEF_PACKET_SIZE 32
#define MAX_PACKET 1024
#define MAX_IP_HDR_SIZE 60
//IP header structure
typedef struct _iphdr
{
unsigned int h_len:4;//Length of the header
unsigned int version:4;//Version of IP
unsigned char tos;//Type of service
unsigned short total_len;//Total length of the packet
unsigned short ident;//Unique identifier
unsigned short frag_and_flags;//Flags
unsigned char ttl;//Time to live
unsigned char proto;//Protocol (TCP,UDP,etc.)
unsigned short checksum;//IP checksum
unsigned int sourceIP;
unsigned int destIP;
} IpHeader;
//ICMP header structure
typedef struct _icmphdr
{
BYTE i_type;
BYTE i_code;//Type sub code
USHORT i_cksum;
USHORT i_id;
USHORT i_seq;
//This is not the standard header, but we reserve space for time
ULONG timestamp;
} IcmpHeader;
//IP option header--use with socket option IP_OPTIONS
typedef struct _ipoptionhdr
{
unsigned char code;//Option type
unsigned char len;//Length of option hdr
unsigned char ptr;//Offset into optons
unsigned long addr[9];//List of IP addrs
} IpOptionHeader;
int datasize;
char* lpdest;
//Print usage information
void usage()
{
printf("usage:MyPing -i:IP [data size]\n");
printf(" -i:IP remote machine to Ping\n");
printf(" datasize can be up to 1 KB\n");
ExitProcess(1);
}
//Helper function to fill in various fields for our ICMP request
void FillICMPData(char* icmp_data, int datasize)
{
IcmpHeader* icmp_hdr = (IcmpHeader*)icmp_data;
icmp_hdr->i_type = ICMP_ECHO;//Request an ICMP echo
icmp_hdr->i_code = 0;
icmp_hdr->i_id = (USHORT)GetCurrentProcessId();
icmp_hdr->i_cksum = 0;
icmp_hdr->i_seq = 0;
char* datapart = icmp_data + sizeof(IcmpHeader);
//Place some junk in the buffer
memset(datapart, 'E', datasize - sizeof(IcmpHeader));
}
//This function calculates the 16-bit one's complement sum
//of the supplied buffer (ICMP) header
USHORT checksum(USHORT* buffer, int size)
{
unsigned long cksum = 0;
while (size > 1)
{
cksum += *buffer++;
size -= sizeof(USHORT);
}
if (size)
{
cksum += *(UCHAR*)buffer;
}
cksum = (cksum>>16) + (cksum & 0xffff);
cksum += (cksum>>16);
return (USHORT)(~cksum);
}
//If the IP option header is present, find the IP options
//within the IP header and print the record route option values
void DecodeIPOptions(char* buf, int bytes)
{
IpOptionHeader* ipopt = (IpOptionHeader*)(buf + 20);
printf("RR: ");
for (int i = 0; i < (ipopt->ptr / 4) - 1; i++)
{
IN_ADDR inaddr;
inaddr.S_un.S_addr = ipopt->addr[i];
if (i != 0)
{
printf(" ");
}
HOSTENT* host = gethostbyaddr((char*)&inaddr.S_un.S_addr,
sizeof(inaddr.S_un.S_addr), AF_INET);
if (host)
{
printf("(%-15s) %s\n", inet_ntoa(inaddr), host->h_name);
}
else
{
printf("(%-15s)\n", inet_ntoa(inaddr));
}
}
return;
}
//The response is an IP packet. We must decode the IP header to
//locate the ICMP data.
void DecodeICMPHeader(char* buf, int bytes, struct sockaddr_in* from)
{
static int icmpcount = 0;
IpHeader* iphdr = (IpHeader*)buf;
//Number of 32-bit words * 4 = bytes
unsigned short iphdrlen = iphdr->h_len * 4;
DWORD tick = GetTickCount();
if ((iphdrlen == MAX_IP_HDR_SIZE) && (!icmpcount))
{
DecodeIPOptions(buf, bytes);
}
if (bytes < iphdrlen + ICMP_MIN)
{
printf("Too few bytes from %s\n", inet_ntoa(from->sin_addr));
}
IcmpHeader* icmphdr = (IcmpHeader*)(buf + iphdrlen);
if (icmphdr->i_type != ICMP_ECHOREPLY)
{
printf("nonecho type %d recvd\n", icmphdr->i_type);
return;
}
//Make sure this is an ICMP reply to something we sent!
if (icmphdr->i_id != (USHORT)GetCurrentProcessId())
{
printf("someone else's packet!\n");
return;
}
printf("%d bytes from %s:", bytes, inet_ntoa(from->sin_addr));
printf(" icmp_seq = %d. ", icmphdr->i_seq);
printf(" time:%d ms", tick - icmphdr->timestamp);
printf("\n");
icmpcount++;
return;
}
void ValidateArgs(int argc, _TCHAR** argv)
{
lpdest = NULL;
datasize = DEF_PACKET_SIZE;
for (int i = 1; i < argc; i++)
{
if ((argv[i][0] == '-') || (argv[i][0] == '/'))
{
switch (tolower(argv[i][1]))
{
case 'i':
lpdest = argv[i] + 3;
break;
default:
usage();
break;
}
}
else if (isdigit(argv[i][0]))
{
datasize = atoi(argv[i]);
}
}
}
int _tmain(int argc, _TCHAR* argv[])
{
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
{
printf("WSAStartup() failed:%d\n", GetLastError());
return -1;
}
ValidateArgs(argc, argv);
SOCKET sockRaw = WSASocket(AF_INET, SOCK_RAW, IPPROTO_ICMP,
NULL, 0, WSA_FLAG_OVERLAPPED);
if (sockRaw == INVALID_SOCKET)
{
printf("WSASocket() failed:%d\n", WSAGetLastError());
return -1;
}
//Set the send/recv timeout values
struct sockaddr_in from;
int fromlen = sizeof(from);
int timeout = 1000;
int bread = setsockopt(sockRaw, SOL_SOCKET, SO_RCVTIMEO,
(char*)&timeout, sizeof(timeout));
if (bread == SOCKET_ERROR)
{
printf("setsockopt(SO_RCVTIMEO) failed:%d\n", WSAGetLastError());
return -1;
}
timeout = 1000;
bread = setsockopt(sockRaw, SOL_SOCKET, SO_SNDTIMEO,(char*)&timeout, sizeof(timeout));
if (bread == SOCKET_ERROR)
{
printf("setsockopt(SO_SNDTIMEO) failed:%d\n", WSAGetLastError());
return -1;
}
struct sockaddr_in dest;
memset(&dest, 0, sizeof(dest));
//Resolve the endpoint's name if necessary
dest.sin_family = AF_INET;
if ((lpdest != NULL) && strlen(lpdest) != 0)
{
dest.sin_addr.s_addr = inet_addr(lpdest);
}
else
{
struct hostent* hp = gethostbyname(lpdest);
if (hp != NULL)
{
memcpy(&(dest.sin_addr), hp->h_addr, hp->h_length);
dest.sin_family = hp->h_addrtype;
printf("dest.sin_addr = %s\n", inet_ntoa(dest.sin_addr));
}
else
{
printf("gethostbyname() failed:%d\n", WSAGetLastError());
return -1;
}
}
//Create the ICMP packet
datasize += sizeof(IcmpHeader);
char* icmp_data = (char*)HeapAlloc(GetProcessHeap(),
HEAP_ZERO_MEMORY, MAX_PACKET);
if (!icmp_data)
{
printf("HeapAlloc() failed:%d\n", GetLastError());
return -1;
}
memset(icmp_data, 0, MAX_PACKET);
FillICMPData(icmp_data, datasize);
char* recvbuf = (char*)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, MAX_PACKET);
//Start sending/receiving ICMP packets
USHORT seq_no = 0;
while (true)
{
static int nCount = 0;
int bwrote;
if (nCount++ == 4)
{
break;
}
((IcmpHeader*)icmp_data)->i_cksum = 0;
((IcmpHeader*)icmp_data)->timestamp = GetTickCount();
((IcmpHeader*)icmp_data)->i_seq = seq_no++;
((IcmpHeader*)icmp_data)->i_cksum = checksum((USHORT*)icmp_data, datasize);
bwrote = sendto(sockRaw, icmp_data, datasize, 0,(struct sockaddr*)&dest, sizeof(dest));
if (bwrote == SOCKET_ERROR)
{
if (WSAGetLastError() == WSAETIMEDOUT)
{
printf("timed out\n");
continue;
}
printf("sendto() failed:%d\n", WSAGetLastError());
return -1;
}
if (bwrote < datasize)
{
printf("Wrote %d bytes\n", bwrote);
}
bread = recvfrom(sockRaw, recvbuf, MAX_PACKET, 0,
(struct sockaddr*)&from, &fromlen);
if (bread == SOCKET_ERROR)
{
if (WSAGetLastError() == WSAETIMEDOUT)
{
printf("timed out\n");
continue;
}
printf("revefrom() failed:%d\n", WSAGetLastError());
return -1;
}
DecodeICMPHeader(recvbuf, bread, &from);
Sleep(1000);
}
//Cleanup
if (sockRaw != INVALID_SOCKET)
{
closesocket(sockRaw);
}
HeapFree(GetProcessHeap(), 0, recvbuf);
HeapFree(GetProcessHeap(), 0, icmp_data);
WSACleanup();
return 0;
}
三、使用Win API調用ICMP.DLL實現、
在這里需要注意的一點是,Windows平台實現ping功能,如果需要使用到IcmpParseReplies函數,需要涉及到兩個動態庫Icmp.dll和Iphlpapi.dll。IcmpParseReplies函數在Windows2000上面由Icmp.dll導出,而在 Windows XP及以后的版本是由Iphlpapi.dll導出的。通過調用LoadLibrary和GetProcAddress來檢測IcmpParseReplies由哪個動態庫導出。優先判斷Iphlpapi.dll是否存在且有導出此函數,如果存在就使用此動態庫,否則再判斷Icmp.dll。
另外隨着IP6的使用,如果業務上涉及到這一塊,也應該要留意。
常用的函數有三個:IcmpCreateFile、IcmpSendEcho、IcmpCloseHandle。具體使用見下實例。
void Ping(char *pIPAddr)
{
HANDLE iHwnd;
iHwnd=IcmpCreateFile();
IPAddr pAddr;
pAddr=(IPAddr)inet_addr (pIPAddr);
icmp_echo_reply pData;
for(int i=1;i<=LoopSend;i++)
{
IcmpSendEcho(iHwnd,pAddr,NULL,0,NULL,(LPVOID)&pData,sizeof(icmp_echo_reply),0);
if (pData.Status==0)
{
printf("Ping測試返回的結果: Time=%dms TTL=%d \n",(int)pData.RoundTripTime,(int)pData.Options.Ttl);
}
else
{
printf("Ping測試失敗...\n");
}
}
if (!IcmpCloseHandle(iHwnd)) printf("Close handle has Error!\n");
}
你可能會發現,用IcmpSendEcho 測試 127.0.0.1的時候,ICMP_ECHO_REPLY.RoundTripTime 會等於0
其實,這個函數是沒有出錯的,即使用Ping 127.0.0.1也是可以的
那么應該怎么去判斷這個函數出錯呢?
用 ICMP_ECHO_REPLY.Status 來獲得測試狀態(記住,當Status為0的時候,函數是正確運行的)
| 常量名 |
值 |
含義 |
| IP_SUCCESS |
0 |
狀態是成功。 |
| IP_BUF_TOO_SMALL |
11001 |
答復緩沖區太小。 |
| IP_DEST_NET_UNREACHABLE |
11002 |
目標網絡不可達。 |
| IP_DEST_HOST_UNREACHABLE |
11003 |
目標主機不可達。 |
| IP_DEST_PROT_UNREACHABLE |
11004 |
目的地的協議是遙不可及。 |
| IP_DEST_PORT_UNREACHABLE |
11005 |
目標端口不可達。 |
| IP_NO_RESOURCES |
11006 |
IP資源不足是可用的。 |
| IP_BAD_OPTION |
11007 |
指定了錯誤的IP選項。 |
| IP_HW_ERROR |
11008 |
一個硬件錯誤。 |
| IP_PACKET_TOO_BIG |
11009 |
包太大。 |
| IP_REQ_TIMED_OUT |
11010 |
請求超時。 |
| IP_BAD_REQ |
11011 |
一個壞的請求。 |
| IP_BAD_ROUTE |
11012 |
一個糟糕的路線。 |
| IP_TTL_EXPIRED_TRANSIT |
11013 |
在傳輸過程中的生存時間(TTL)的過期。 |
| IP_TTL_EXPIRED_REASSEM |
11014 |
在碎片重組過程中的生存時間過期。 |
| IP_PARAM_PROBLEM |
11015 |
一個參數的問題。 |
| IP_SOURCE_QUENCH |
11016 |
數據報到達太快,處理和數據報可能被丟棄。 |
| IP_OPTION_TOO_BIG |
11017 |
一個IP選項是太大了。 |
| IP_BAD_DESTINATION |
11018 |
一個壞的目的地。 |
| IP_GENERAL_FAILURE |
11050 |
一般故障。這個錯誤可以返回一些畸形的ICMP數據包 |
要了解Ping的原理,我們先來了解下ping命令的使用
通過發送“網際消息控制協議 (ICMP)”回響請求消息來驗證與另一台 TCP/IP 計算機的 IP 級連接。回響應答消息的接收情況將和往返過程的次數一起顯示出來。Ping 是用於檢測網絡連接性、可到達性和名稱解析的疑難問題的主要 TCP/IP 命令。
語法
ping [-t] [-a] [-n Count] [-l Size] [-f] [-i TTL] [-v TOS] [-r Count] [-s Count] [{-j HostList | -k HostList}] [-w Timeout] [TargetName]
-t
指定在中斷前 ping 可以持續發送回響請求信息到目的地。要中斷並顯示統計信息,請按 CTRL-BREAK。要中斷並退出 ping,請按 CTRL-C。
-a
指定對目的地 IP 地址進行反向名稱解析。如果解析成功,ping 將顯示相應的主機名。
-n Count
指定發送回響請求消息的次數。默認值為 4。
-lSize
指定發送的回響請求消息中“數據”字段的長度(以字節表示)。默認值為 32。size 的最大值是 65,527。
-f
指定發送的回響請求消息帶有“不要拆分”標志(所在的 IP 標題設為 1)。回響請求消息不能由目的地路徑上的路由器進行拆分。該參數可用於檢測並解決“路徑最大傳輸單位 (PMTU)”的故障。
-i TTL
指定發送回響請求消息的 IP 標題中的 TTL 字段值。其默認值是是主機的默認 TTL 值。對於 Windows XP 主機,該值一般是 128。TTL 的最大值是 255。
-v TOS
指定發送回響請求消息的 IP 標題中的“服務類型 (TOS)”字段值。默認值是 0。TOS 被指定為 0 到 255 的十進制數。
-r Count
指定 IP 標題中的“記錄路由”選項用於記錄由回響請求消息和相應的回響應答消息使用的路徑。路徑中的每個躍點都使用“記錄路由”選項中的一個值。如果可能,可以指定一個等於或大於來源和目的地之間躍點數的 Count。Count 的最小值必須為 1,最大值為 9。
-s Count
指定 IP 標題中的“Internet 時間戳”選項用於記錄每個躍點的回響請求消息和相應的回響應答消息的到達時間。Count 的最小值必須為 1,最大值為 4。
-jPath
指定回響請求消息使用帶有 HostList 指定的中間目的地集的 IP 標題中的“稀疏資源路由”選項。可以由一個或多個具有松散源路由的路由器分隔連續中間的目的地。主機列表中的地址或名稱的最大數為 9,主機列表是一系列由空格分開的 IP 地址(帶點的十進制符號)。
-k HostList
指定回響請求消息使用帶有 HostList 指定的中間目的地集的 IP 標題中的“嚴格來源路由”選項。使用嚴格來源路由,下一個中間目的地必須是直接可達的(必須是路由器接口上的鄰居)。主機列表中的地址或名稱的最大數為 9,主機列表是一系列由空格分開的 IP 地址(帶點的十進制符號)。
-w Timeout
指定等待回響應答消息響應的時間(以微妙計),該回響應答消息響應接收到的指定回響請求消息。如果在超時時間內未接收到回響應答消息,將會顯示“請求超時”的錯誤消息。默認的超時時間為 4000(4 秒 )。
TargetName
指定目的端,它既可以是 IP 地址,也可以是主機名。
/?
在命令提示符顯示幫助。
每個ICMP報文都有自己的格式,但它們開始的三個字段都是一樣的:一個8位的報文類型(type)用來標識報文,一個8位的代碼(code)用來 提供有關類型的進一步信息,一個16位的校驗和(checksum)。(ICMP采用和IP相同的校驗和算法,但ICMP校驗和只覆蓋ICMP報文)。這 里我們給出ICMP報文首部的數據結構:
struct ICMPHEADER
{
BYTE i_type; // 類型
BYTE i_code; // 代碼
USHORT i_cksum; // 首部校驗和
USHORT i_id; // 標識
USHORT i_seq; // 序列號
ULONG timestamp; // 時間戳(選用)
};
下表表示了ICMP的報文類型及其含義:
| TYPE |
CODE |
Description |
Query |
Error |
| 0 |
0 |
Echo Reply——回顯應答(Ping應答) |
x |
|
| 3 |
0 |
Network Unreachable——網絡不可達 |
|
x |
| 3 |
1 |
Host Unreachable——主機不可達 |
|
x |
| 3 |
2 |
Protocol Unreachable——協議不可達 |
|
x |
| 3 |
3 |
Port Unreachable——端口不可達 |
|
x |
| 3 |
4 |
Fragmentation needed but no frag. bit set——需要進行分片但設置不分片比特 |
|
x |
| 3 |
5 |
Source routing failed——源站選路失敗 |
|
x |
| 3 |
6 |
Destination network unknown——目的網絡未知 |
|
x |
| 3 |
7 |
Destination host unknown——目的主機未知 |
|
x |
| 3 |
8 |
Source host isolated (obsolete)——源主機被隔離(作廢不用) |
|
x |
| 3 |
9 |
Destination network administratively prohibited——目的網絡被強制禁止 |
|
x |
| 3 |
10 |
Destination host administratively prohibited——目的主機被強制禁止 |
|
x |
| 3 |
11 |
Network unreachable for TOS——由於服務類型TOS,網絡不可達 |
|
x |
| 3 |
12 |
Host unreachable for TOS——由於服務類型TOS,主機不可達 |
|
x |
| 3 |
13 |
Communication administratively prohibited by filtering——由於過濾,通信被強制禁止 |
|
x |
| 3 |
14 |
Host precedence violation——主機越權 |
|
x |
| 3 |
15 |
Precedence cutoff in effect——優先中止生效 |
|
x |
| 4 |
0 |
Source quench——源端被關閉(基本流控制) |
|
|
| 5 |
0 |
Redirect for network——對網絡重定向 |
|
|
| 5 |
1 |
Redirect for host——對主機重定向 |
|
|
| 5 |
2 |
Redirect for TOS and network——對服務類型和網絡重定向 |
|
|
| 5 |
3 |
Redirect for TOS and host——對服務類型和主機重定向 |
|
|
| 8 |
0 |
Echo request——回顯請求(Ping請求) |
x |
|
| 9 |
0 |
Router advertisement——路由器通告 |
|
|
| 10 |
0 |
Route solicitation——路由器請求 |
|
|
| 11 |
0 |
TTL equals 0 during transit——傳輸期間生存時間為0 |
|
x |
| 11 |
1 |
TTL equals 0 during reassembly——在數據報組裝期間生存時間為0 |
|
x |
| 12 |
0 |
IP header bad (catchall error)——壞的IP首部(包括各種差錯) |
|
x |
| 12 |
1 |
Required options missing——缺少必需的選項 |
|
x |
| 13 |
0 |
Timestamp request (obsolete)——時間戳請求(作廢不用) |
x |
|
| 14 |
|
Timestamp reply (obsolete)——時間戳應答(作廢不用) |
x |
|
| 15 |
0 |
Information request (obsolete)——信息請求(作廢不用) |
x |
|
| 16 |
0 |
Information reply (obsolete)——信息應答(作廢不用) |
x |
|
| 17 |
0 |
Address mask request——地址掩碼請求 |
x |
|
| 18 |
0 |
Address mask reply——地址掩碼應答 |
|
|
