先來說說ping程式的原理吧,其實挺簡單,就是一個主機系統向另外一個主機系統說:I love you(ICMP報文),然後那個主機如果相信你或者說想和你通訊,和你心知心,那它就把收到的I love you(ICMP)報文原樣返回.好嘛,源主機收到這個回應後,就happy了,因為對方是和自己心連心的。如果對方沒有收到這個訊息,或者對你不感冒,不願意理你,不回你這個報文,或者說些不知雲是雲霧是霧的話,對不起啦,感情是兩個人的事情哦.
要想深刻瞭解,需有入目三分的實力,這個ping也一樣,咱們先來看看它採用的TCP/IP協議,我剛說了,它發送的是ICMP回應要求,回答的是回顯應答報文。談起這個ICMP(Internet Control Message,網際控制報文協議)是為網關和目標主機而提供的一種差錯控制機制,使它們在遇到差錯時能把錯誤報表給報文源發方.是IP層的一個協議。但是由於差錯報告在發送給報文源發方時可能也要經過若干子網,因此牽涉到路由選擇等問題,所以ICMP報文需通過IP協議來發送。ICMP資料報的資料發送前需要兩級封裝:首先添加ICMP前序形成ICMP報文,再添加IP前序形成IP資料報。如所示:
由於IP層協議是一種點對點的協議,而非端對端的協議,它提供不需連線的資料報服務,沒有連接埠的概念,因此很少使用bind()和connect() 函數,若有使用也只是用於設定IP地址。發送資料使用sendto()函數,接收資料使用recvfrom()函數。
TCP/IP的經典大作《TCP/IP協議詳解.卷一》清晰的告訴我,IP前序格式如下:
詳細的,小王那懶的人都知道翻翻上面提到的書,我也就不詳細介紹了,我這裡給出linux中的資料結構實現:
struct ip {#if __BYTE_ORDER == __LITTLE_ENDIAN unsigned int ip_hl:4; /* header length */ unsigned int ip_v:4; /* version */#endif#if __BYTE_ORDER == __BIG_ENDIAN unsigned int ip_v:4; /* version */ unsigned int ip_hl:4; /* header length */#endif u_int8_t ip_tos; /* type of service */ u_short ip_len; /* total length */ u_short ip_id; /* identification */ u_short ip_off; /* fragment offset field */#define IP_RF 0x8000 /* reserved fragment flag */#define IP_DF 0x4000 /* dont fragment flag */#define IP_MF 0x2000 /* more fragments flag */#define IP_OFFMASK 0x1fff /* mask for fragmenting bits */ u_int8_t ip_ttl; /* time to live */ u_int8_t ip_p; /* protocol */ u_short ip_sum; /* checksum */ struct in_addr ip_src, ip_dst; /* source and dest address */ };
別看這多,其實ping程式用到的沒幾個:
(1)IP前序長度IHL(Internet Header Length)以4位元組為一個單位來記錄IP前序的長度,是上述IP資料結構的ip_hl變數。
(2)存留時間TTL(Time To Live)以秒為單位,指出IP資料報能在網路上停留的最長時間,其值由發送方設定,並在經過路由的每一個節點時減一,當該值為0時,資料報將被丟棄,是上述IP資料結構的ip_ttl變數。ICMP報文分為兩種:查詢報文和差錯報文。每個ICMP前序均包含類型、編碼和校正和這三項內容,其餘選項則隨ICMP的功能不同而不同。ICMP報文格式如下:
Ping命令只使用眾多ICMP報文中的兩種:"請求回送'(ICMP_ECHO)和"請求回應'(ICMP_ECHOREPLY)。在Linux中定義如下:
#define ICMP_ECHO 0#define ICMP_ECHOREPLY 8
|
在Linux中ICMP資料結構(<netinet/ip_icmp.h>)定義如下:
linux中ICMP資料結構struct icmp{ u_int8_t icmp_type; /* type of message, see below */ u_int8_t icmp_code; /* type sub code */ u_int16_t icmp_cksum; /* ones complement checksum of struct */ union { u_char ih_pptr; /* ICMP_PARAMPROB */ struct in_addr ih_gwaddr; /* gateway address */ struct ih_idseq /* echo datagram */ { u_int16_t icd_id; u_int16_t icd_seq; } ih_idseq; u_int32_t ih_void; /* ICMP_UNREACH_NEEDFRAG -- Path MTU Discovery (RFC1191) */ struct ih_pmtu { u_int16_t ipm_void; u_int16_t ipm_nextmtu; } ih_pmtu; struct ih_rtradv { u_int8_t irt_num_addrs; u_int8_t irt_wpa; u_int16_t irt_lifetime; } ih_rtradv; } icmp_hun;#define icmp_pptr icmp_hun.ih_pptr#define icmp_gwaddr icmp_hun.ih_gwaddr#define icmp_id icmp_hun.ih_idseq.icd_id#define icmp_seq icmp_hun.ih_idseq.icd_seq#define icmp_void icmp_hun.ih_void#define icmp_pmvoid icmp_hun.ih_pmtu.ipm_void#define icmp_nextmtu icmp_hun.ih_pmtu.ipm_nextmtu#define icmp_num_addrs icmp_hun.ih_rtradv.irt_num_addrs#define icmp_wpa icmp_hun.ih_rtradv.irt_wpa#define icmp_lifetime icmp_hun.ih_rtradv.irt_lifetime union { struct { u_int32_t its_otime; u_int32_t its_rtime; u_int32_t its_ttime; } id_ts; struct { struct ip idi_ip; /* options and then 64 bits of data */ } id_ip; struct icmp_ra_addr id_radv; u_int32_t id_mask; u_int8_t id_data[1]; } icmp_dun;#define icmp_otime icmp_dun.id_ts.its_otime#define icmp_rtime icmp_dun.id_ts.its_rtime#define icmp_ttime icmp_dun.id_ts.its_ttime#define icmp_ip icmp_dun.id_ip.idi_ip#define icmp_radv icmp_dun.id_radv#define icmp_mask icmp_dun.id_mask#define icmp_data icmp_dun.id_data}; |
Ping命令中需要顯示的資訊,包括icmp_seq和ttl都已有實現的辦法,但還缺rtt往返時間。為了實現這一功能,可利用ICMP資料報攜帶一個時間戳記。使用以下函數產生時間戳記:
#include int gettimeofday(struct timeval *tp,void *tzp)其中timeval結構如下: struct timeval{ long tv_sec; long tv_usec;} |
在發送和接收報文時由gettimeofday分別產生兩個timeval結構,兩者之差即為往返時間,即 ICMP報文發送與接收的時間差,而timeval結構由ICMP資料報攜帶,
tzp指標表示時區,一般都不使用,賦NULL值。系統內建的ping命令當它接送完所有ICMP報文後,會對所有發送和所有接收的ICMP報文進行統計,從而計算ICMP報文丟失的比率。為達此目的,定義兩個全域變數:接收計數器和發送計數器,用於記錄ICMP報文接受和發送數目。丟失數目=發送總數-接收總數,丟失比率=丟失數目/發送總數。現給出類比Ping程式功能的代碼如下:
void statistics(int signo){ printf("\n--------------------PING statistics-------------------\n"); printf("%d packets transmitted, %d received , %d%% lost\n", nsend,nreceived,(nsend-nreceived)/nsend*100); close(sockfd); exit(1);}/*校正和演算法*/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 i,packsize; struct icmp *icmp; struct timeval *tval; icmp=(struct icmp*)sendpacket; icmp->icmp_type=ICMP_ECHO; icmp->icmp_code=0; icmp->icmp_cksum=0; icmp->icmp_seq=pack_no; icmp->icmp_id=pid; packsize=8+datalen; 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; while( nsend<MAX_NO_PACKETS) //發送MAX_NO_PACKETS個ICMP報文 { nsend++; packetsize=pack(nsend); /*設定ICMP前序*/ //sendpacket為要發送的內容,由pack()函數設定,dest_addr是目的地址, if( sendto(sockfd,sendpacket,packetsize,0, (struct sockaddr *)&dest_addr,sizeof(dest_addr) )<0 ) { perror("sendto error"); continue; } sleep(1); /*每隔一秒發送一個ICMP報文*/ }}/*接收所有ICMP報文*/void recv_packet(){ int n,fromlen; extern int errno; signal(SIGALRM,statistics); fromlen=sizeof(from); while( nreceived<nsend) { //alarm()用來設定訊號SIGALRM在經過參數seconds指定的秒數後傳送給目前的進程 alarm(MAX_WAIT_TIME); if( (n=recvfrom(sockfd,recvpacket,sizeof(recvpacket),0, (struct sockaddr *)&from,&fromlen)) <0) { if(errno==EINTR) continue; perror("recvfrom error"); continue; } gettimeofday(&tvrecv,NULL); /*記錄接收時間*/ if(unpack(recvpacket,n)==-1)continue; nreceived++; }}/*剝去ICMP前序*/int unpack(char *buf,int len){ int i,iphdrlen; struct ip *ip; struct icmp *icmp; struct timeval *tvsend; double rtt; ip=(struct ip *)buf; //求ip前序長度,即ip前序的長度標誌乘4,頭長度指明頭中包含的4位元組字的個數。可接受 //的最小值是5,最大值是15 iphdrlen=ip->ip_hl<<2; icmp=(struct icmp *)(buf+iphdrlen); /*越過ip前序,指向ICMP前序*/ len-=iphdrlen; /*ICMP前序及ICMP資料報的總長度*/ if( len<8) /*小於ICMP前序長度則不合理*/ { printf("ICMP packets\'s length is less than 8\n"); return -1; } /*確保所接收的是我所發的的ICMP的回應*/ if( (icmp->icmp_type==ICMP_ECHOREPLY) && (icmp->icmp_id==pid) ) { tvsend=(struct timeval *)icmp->icmp_data; tv_sub(&tvrecv,tvsend); /*接收和發送的時間差*/ rtt=tvrecv.tv_sec*1000+tvrecv.tv_usec/1000; /*以毫秒為單位計算rtt*/ /*顯示相關資訊*/ printf("%d byte from %s: icmp_seq=%u ttl=%d rtt=%.3f ms\n", len,inet_ntoa(from.sin_addr),icmp->icmp_seq,ip->ip_ttl,rtt); } else return -1;}int main(int argc,char *argv[]){ struct hostent *host; struct protoent *protocol; unsigned long inaddr=0l; int waittime=MAX_WAIT_TIME; //#define MAX_WAIT_TIME 5 int size=50*1024; if(argc<2) { printf("usage:%s hostname/IP address\n",argv[0]); exit(1); } //getprotobyname("icmp")返回對應於給定協議名的包含名字和協議號的protoent結構指標。 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[1])==INADDR_NONE) { if((host=gethostbyname(argv[1]) )==NULL) /*是主機名稱*/ { perror("gethostbyname error"); exit(1); } memcpy( (char *)&dest_addr.sin_addr,host->h_addr,host->h_length); } else /*是ip地址*/ dest_addr.sin_addr.s_addr = inet_addr(argv[1]); /*擷取main的進程id,用於設定ICMP的標誌符*/ pid=getpid(); printf("PING %s(%s): %d bytes data in ICMP packets.\n",argv[1], inet_ntoa(dest_addr.sin_addr),datalen); send_packet(); /*發送所有ICMP報文*/ recv_packet(); /*接收所有ICMP報文*/ statistics(SIGALRM); /*進行統計*/ return 0;}/*兩個timeval結構相減*/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;}
好了,編譯,運行。按照正常的ping程式運行(當然了,這個程式還是很簡單,目前為止還不支援迴路位址127.0.0.1)。