1. 程式人生 > >用C語言實現Ping程式功能(轉)

用C語言實現Ping程式功能(轉)

用C語言實現Ping程式功能

日期:2006-12-25 作者:樑俊輝 來自:IBM DW中國

大部分人用ping命令只是作為檢視另一個系統的網路連線是否正常的一種簡單方法。在這篇文章中,作者將介紹如何用C語言編寫一個模擬ping命令功能的程式。

ping命令是用來檢視網路上另一個主機系統的網路連線是否正常的一個工具。ping命令的工作原理是:向網路上的另一個主機系統傳送ICMP報文,如果指定系統得到了報文,它將把報文一模一樣地傳回給傳送者,這有點象潛水艇聲納系統中使用的發聲裝置。

例如,在Linux終端上執行ping localhost命令將會看到以下結果:



PING localhost.localdomain (127.0.0.1) from 127.0.0.1 : 56(84) bytes of data.

64 bytes from localhost.localdomain (127.0.0.1): icmp_seq=0 ttl=255 time=112 usec

64 bytes from localhost.localdomain (127.0.0.1): icmp_seq=1 ttl=255 time=79 usec

64 bytes from localhost.localdomain (127.0.0.1): icmp_seq=2 ttl=255 time=78 usec

64 bytes from localhost.localdomain (127.0.0.1): icmp_seq=3 ttl=255 time=82 usec



--- localhost.localdomain ping statistics ---

4 packets transmitted, 4 packets received, 0% packet loss

round-trip min/avg/max/mdev = 0.078/0.087/0.112/0.018 ms

由上面的執行結果可以看到,ping命令執行後顯示出被測試系統主機名和相應IP地址、返回給當前主機的ICMP報文順序號、ttl生存時間和往返時間rtt(單位是毫秒,即千分之一秒)。要寫一個模擬ping命令,這些資訊有啟示作用。

要真正瞭解ping命令實現原理,就要了解ping命令所使用到的TCP/IP協議。

ICMP(Internet Control Message,網際控制報文協議)是為閘道器和目標主機而提供的一種差錯控制機制,使它們在遇到差錯時能把錯誤報告給報文源發方。ICMP協議是IP層的一個協議,但是由於差錯報告在傳送給報文源發方時可能也要經過若干子網,因此牽涉到路由選擇等問題,所以ICMP報文需通過IP協議來發送。ICMP資料報的資料傳送前需要兩級封裝:首先新增ICMP報頭形成ICMP報文,再新增IP報頭形成IP資料報。如下圖所示

IP報頭
ICMP報頭
ICMP資料報

由於IP層協議是一種點對點的協議,而非端對端的協議,它提供無連線的資料報服務,沒有埠的概念,因此很少使用bind()和connect()函式,若有使用也只是用於設定IP地址。傳送資料使用sendto()函式,接收資料使用recvfrom()函式。IP報頭格式如下圖:


在Linux中,IP報頭格式資料結構()定義如下:



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程式只使用以下資料:

  • IP報頭長度IHL(Internet Header Length)�D�D以4位元組為一個單位來記錄IP報頭的長度,是上述IP資料結構的ip_hl變數。
  • 生存時間TTL(Time To Live)�D�D以秒為單位,指出IP資料報能在網路上停留的最長時間,其值由傳送方設定,並在經過路由的每一個節點時減一,當該值為0時,資料報將被丟棄,是上述IP資料結構的ip_ttl變數。

ICMP報文分為兩種,一是錯誤報告報文,二是查詢報文。每個ICMP報頭均包含型別、編碼和校驗和這三項內容,長度為8位,8位和16位,其餘選項則隨ICMP的功能不同而不同。

Ping命令只使用眾多ICMP報文中的兩種:"請求回送'(ICMP_ECHO)和"請求迴應'(ICMP_ECHOREPLY)。在Linux中定義如下:



#define ICMP_ECHO 0

#define ICMP_ECHOREPLY 8

這兩種ICMP型別報頭格式如下:


在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

};

使用巨集定義令表達更簡潔,其中ICMP報頭為8位元組,資料報長度最大為64K位元組。

  1. 校驗和演算法�D�D這一演算法稱為網際校驗和演算法,把被校驗的資料16位進行累加,然後取反碼,若資料位元組長度為奇數,則資料尾部補一個位元組的0以湊成偶數。此演算法適用於IPv4、ICMPv4、IGMPV4、ICMPv6、UDP和TCP校驗和,更詳細的資訊請參考RFC1071,校驗和欄位為上述ICMP 資料結構的icmp_cksum變數。
  2. 識別符號�D�D用於唯一標識ICMP報文, 為上述ICMP資料結構的icmp_id巨集所指的變數。
  3. 順序號�D�Dping命令的icmp_seq便由這裡讀出,代表ICMP報文的傳送順序,為上述ICMP資料結構的icmp_seq巨集所指的變數。

Ping命令中需要顯示的資訊,包括icmp_seq和ttl都已有實現的辦法,但還缺rtt往返時間。為了實現這一功能,可利用ICMP資料報攜帶一個時間戳。使用以下函式生成時間戳:



#include

int gettimeofday(struct timeval *tp,void *tzp)

其中timeval結構如下:

       struct timeval{

           long tv_sec;

           long tv_usec;

       }

其中tv_sec為秒數,tv_usec微秒數。在傳送和接收報文時由gettimeofday分別生成兩個timeval結構,兩者之差即為往返時間,即 ICMP報文傳送與接收的時間差,而timeval結構由ICMP資料報攜帶,tzp指標表示時區,一般都不使用,賦NULL值。

資料統計

系統自帶的ping命令當它接送完所有ICMP報文後,會對所有傳送和所有接收的ICMP報文進行統計,從而計算ICMP報文丟失的比率。為達此目的,定義兩個全域性變數:接收計數器和傳送計數器,用於記錄ICMP報文接受和傳送數目。丟失數目=傳送總數-接收總數,丟失比率=丟失數目/傳送總數。

現給出模擬Ping程式功能的程式碼如下:



/***********************************************************

* 作者:樑俊輝 *

* 時間:2001年10月 *

* 名稱:myping.c *

* 說明:本程式用於演示ping命令的實現原理 *

***********************************************************/

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include



#define PACKET_SIZE 4096

#define MAX_WAIT_TIME 5

#define MAX_NO_PACKETS 3



char sendpacket[PACKET_SIZE];

char recvpacket[PACKET_SIZE];

int sockfd,datalen=56;

int nsend=0,nreceived=0;

struct sockaddr_in dest_addr;

pid_t pid;

struct sockaddr_in from;

struct timeval tvrecv;



void statistics(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);



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 { nsend++;

packetsize=pack(nsend); /*設定ICMP報頭*/

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 { 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;

iphdrlen=ip->ip_hl<<2; /*求ip報頭長度,即ip報頭的長度標誌乘4*/

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;

}



main(int argc,char *argv[])

{ struct hostent *host;

struct protoent *protocol;

unsigned long inaddr=0l;

int waittime=MAX_WAIT_TIME;

int size=50*1024;



if(argc<2)

{ printf("usage:%s hostname/IP address/n",argv[0]);

exit(1);

}



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;



   if((host=gethostbyname(argv[1]) )==NULL) /*是主機名*/
   {      
perror("gethostbyname error");
                exit(1);
       }
        memcpy( (char *)&dest_addr.sin_addr,host->h_addr,host->h_length);
   

/*獲取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;

}

/*------------- The End -----------*/

特別注意

只有root使用者才能利用socket()函式生成原始套接字,要讓Linux的一般使用者能執行以上程式,需進行如下的特別操作:

用root登陸,編譯以上程式:gcc -o myping myping.c,其目的有二:一是編譯,二是讓myping屬於root使用者。

再執行chmod u+s myping,目的是把myping程式設成SUID的屬性。

退出root,用一般使用者登陸,執行./myping www.cn.ibm.com,有以下執行結果:



PING www.cn.ibm.com(202.95.2.148): 56 bytes data in ICMP packets.

64 byte from 202.95.2.148: icmp_seq=1 ttl=242 rtt=3029.000 ms

64 byte from 202.95.2.148: icmp_seq=2 ttl=242 rtt=2020.000 ms

64 byte from 202.95.2.148: icmp_seq=3 ttl=242 rtt=1010.000 ms



--------------------PING statistics-------------------

3 packets transmitted, 3 received , %0 lost


由於myping.c是傳送完所有的ICMP報文才去接收,因此第一、第二和第三個ICMP報文的往返時間依此是3秒,2秒,1秒,上述結果中rtt資訊正反映這一事實。