轉自百度文庫。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <unistd.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/ip_icmp.h>
#include <netdb.h>
#include <setjmp.h>
#include <errno.h>
#define PACKET_SIZE 4096
#define MAX_WAIT_TIME 3
char sendpacket[PACKET_SIZE];
char recvpacket[PACKET_SIZE];
int sockfd, datalen = 56;
int nsend = 0, nreceived = 0;
struct sockaddr_in dest_addr;
struct protoent *protocol;
pid_t pid;
struct sockaddr_in from;
struct timeval tvrecv;
double min_rtt = MAX_WAIT_TIME, max_rtt = 0.0, sum_rtt = 0.0;
void statistics( int signo );
void timeout( int signo );
unsigned short cal_chksum( unsigned short *addr, int len );
int pack( int pack_no );
void send_packet( void );
void recv_packet( void );
int unpack( char *buf, int len );
void tv_sub( struct timeval *out, struct timeval *in );
int main( int argc, char *argv[] )
{
struct hostent *host;
unsigned long inaddr = 0l;
int size = 50 * 1024;
int destLocation = 1;
//目的地參數所在位置
int sendCount = 0;
//發送資料包個數
if( argc < 2 )
{
printf( "Usage:%s destination\n", argv[0] );
exit( 1 );
}
else
{
int AC = 1;
//參數計數器
while( AC < argc )
{
if( argv[AC][0] == '-' )
//有選項參數
{
if( argv[AC][1] == 'c' )
//指定發送包個數
{
if( strlen(argv[AC]) == 2 )
{
AC++;
sendCount = atoi(argv[AC]);
}
else
sendCount = atoi(&argv[AC][2]);
}
else if( argv[AC][1] == 's' )
//指定發送包資料大小
{
if( strlen(argv[AC]) == 2 )
{
AC++;
datalen = atoi(argv[AC]);
}
else
datalen = atoi(&argv[AC][2]);
}
}
else //是目的地參數
destLocation = AC;
AC++;
}
}
if( (protocol = getprotobyname( "icmp" )) == NULL ) //獲得協議資訊
{
perror( "getprotobyname" );
exit( 1 );
}
//產生使用ICMP的原始通訊端,只有root才能產生
if( (sockfd = socket( AF_INET, SOCK_RAW, protocol->p_proto )) < 0 )
{
perror( "socket error" );
exit( 1 );
}
//回收root許可權,設定目前使用者許可權
setuid( getuid() );
//擴大通訊端接收緩衝區到50K。這樣做主要為了減小接收緩衝區溢位的可能性,
//若無意中ping一個廣播位址或多播地址,將會引來大量應答。
setsockopt( sockfd, SOL_SOCKET, SO_RCVBUF, &size, sizeof(size) );
bzero( &dest_addr, sizeof(dest_addr) );
dest_addr.sin_family = AF_INET;
//判斷是主機名稱還是IP地址
if( (inaddr = inet_addr( argv[destLocation] )) == INADDR_NONE )
{ //不是點分十進位
if( (host = gethostbyname( argv[destLocation] )) == NULL )
{
perror( "gethostbyname error" );
exit( 1 );
} //是主機名稱
memcpy( (char *)&dest_addr.sin_addr, host->h_addr, host->h_length );
}
else //是IP地址
memcpy( (char *)&dest_addr.sin_addr, (char *)&inaddr, sizeof(inaddr) );
//擷取main的進程id,用於設定ICMP的標誌符
pid = getpid();
printf( "PING %s(%s): %d bytes of data in ICMP packets.\n", argv[destLocation],
inet_ntoa( dest_addr.sin_addr ), datalen );
signal( SIGINT, statistics );
//若從鍵盤中斷則直接進行統計輸出
while( 1 )
{
send_packet();
recv_packet();
sleep( 1 );
//每隔一秒發送一個ICMP報文
if( sendCount == 0 )
continue;
else if( nsend == sendCount )
break;
}
statistics( SIGTERM );
//正常結束進行統計輸出
return 0;
}
//進行統計
void statistics( int signo )
{
close( sockfd );
//在統計時關閉sockfd
printf( "\n--------------------PING statistics-------------------\n" );
printf( "%d packets transmitted, %d received , %.0f%% packet loss\n",
nsend, nreceived, (nsend - nreceived) / (double)nsend * 100.0 );
if( min_rtt < MAX_WAIT_TIME)
//沒有ping通,以下不會顯示
{
printf( "rtt min/avg/max = %.3f/%.3f/%.3f ms\n", min_rtt,
sum_rtt / nreceived, max_rtt );
}
exit( 1 );
}
//逾時處理
void timeout( int signo )
{
printf( "Request timed out.\n" );
}
//計算校正和
unsigned short cal_chksum( unsigned short *addr, int len )
{
int nleft = len;
int sum = 0;
unsigned short *w = addr;
unsigned short answer = 0;
//把ICMP前序位元據以2位元組為單位累加起來
while( nleft > 1 )
{
sum += *w++;
nleft -= 2;
}
//若ICMP前序為奇數個位元組,會剩下最後一位元組。
//把最後一個位元組視為一個2位元組資料的高位元組,這個2位元組資料的低位元組為0,繼續累加。
if( nleft == 1 )
{
*(unsigned char *)(&answer) = *(unsigned char *)w;
sum += answer;
}
sum = (sum >> 16) + (sum & 0xffff);
sum += (sum >> 16);
answer = ~sum;
return answer;
}
//設定ICMP前序
int pack( int pack_no )
{
int packsize;
struct icmp *icmp;
struct timeval *tval;
icmp = (struct icmp*)sendpacket;
icmp->icmp_type = ICMP_ECHO;
//ICMP報文類型
icmp->icmp_code = 0;
//編碼(未使用)
icmp->icmp_cksum = 0;
//初始化校正和
icmp->icmp_seq = pack_no;
//發送序號
icmp->icmp_id = pid;
//唯一標識ICMP報文
packsize = 8 + datalen;
//ICMP報文頭部共8位元組
tval = (struct timeval *)icmp->icmp_data;
gettimeofday( tval, NULL );
//記錄發送時間
icmp->icmp_cksum = cal_chksum( (unsigned short *)icmp, packsize );//校正和
return packsize;
}
//發送一條ICMP報文
void send_packet()
{
int packetsize;
packetsize = pack( nsend + 1 );
//設定ICMP前序
if( sendto( sockfd, sendpacket, packetsize, 0,
(struct sockaddr *)&dest_addr, sizeof(dest_addr) ) < 0 )
{
perror( "sendto error" );
return;
}
nsend++;
}
//接收一條ICMP報文
void recv_packet()
{
int n, fromlen;
extern int errno;
signal( SIGALRM, timeout );//等待MAX_WAIT_TIME無響應則直接進入逾時處理
alarm( MAX_WAIT_TIME );
//設定最長等待時間
do
{
if( (n = recvfrom( sockfd, recvpacket, sizeof(recvpacket), 0,
(struct sockaddr *)&from, &fromlen )) < 0 )
{
if( errno == EINTR )
//被訊號中斷
return;
perror( "recvfrom error" );
return;
}
gettimeofday( &tvrecv, NULL );
//記錄接收時間
} //收到前面逾時或非ECHOREPLY的報文則再取下一條報文
while( unpack( recvpacket, n ) == 1 );
alarm( MAX_WAIT_TIME );
//設定最長等待時間
}
//剝去ICMP前序並處理ICMP資訊
int unpack( char *buf, int len )
{
int iphdrlen;
struct ip *ip;
struct icmp *icmp;
struct timeval *tvsend;
double rtt;
ip = (struct ip *)buf;
iphdrlen = ip->ip_hl << 2;
//求ip前序長度,即ip前序的長度標誌乘以4
icmp = (struct icmp *)(buf + iphdrlen);
//越過ip前序,指向ICMP前序
if( ip->ip_p == protocol->p_proto && icmp->icmp_seq == nsend &&
icmp->icmp_type == ICMP_ECHOREPLY )
{
len -= iphdrlen;
//ICMP報文的總長度
if( len < 8 )
//小於ICMP前序長度則不合理
{
printf( "ICMP packets\'s length is less than 8\n" );
return -1;
}
//確保所接收的是本程式所發的的ICMP的回應
if( icmp->icmp_id == pid )
{
nreceived++;
//收到正確的報文
tvsend = (struct timeval *)icmp->icmp_data;
tv_sub( &tvrecv, tvsend );
//計算接收和發送的時間差
rtt = tvrecv.tv_sec * (double)1000 + tvrecv.tv_usec / (double)1000;
printf( "%d bytes from %s: icmp_seq=%u ttl=%d time=%.3f ms\n", len,
inet_ntoa( from.sin_addr ), icmp->icmp_seq, ip->ip_ttl, rtt );
if( rtt < min_rtt )
min_rtt = rtt;
if( rtt > max_rtt )
max_rtt = rtt;
sum_rtt += rtt;
return 0;
}
else
return -1;
}
else //收到非ICMP報文或前面逾時的報文則不再處理
return 1;
}
//計算時間差
void tv_sub( struct timeval *out, struct timeval *in )
{
if( (out->tv_usec -= in->tv_usec) < 0 )
{
--out->tv_sec;
out->tv_usec += 1000000;
}
out->tv_sec -= in->tv_sec;
}