Linux下ping命令實現詳解

相信大家一定遇到過上不了網的情形,都知道用個ping命令。這不小王就是這樣的女孩,老是上不了網,老是找我,我就先ping一下,逐步找找問題在哪兒,有的放矢,不至於盲目抓瞎(說心裏話,我真不願意幫小王弄,每次弄好了,她就和那個叫寒煙的Q友,使勁聊天,唉,心裏哇涼啊.)都說實踐是最好的老師,小王不和老師我聊天,說明我這個老師沒做好,沒關係,我有技術我怕誰,抓住小王的心,我還是有把握的。不知誰問:刀是什麼樣的刀,朱鏽斷環刀;劍是什麼樣的劍,流光翠月劍!不要問我爲啥這大反差,沒辦法,誰叫小王喜歡呢。唉,不說了,小王把眨巴着眼催我快點呢.

     好,今天就給大家講講有關linux下ping程序的實現,以後誰再找我修網,對不起,該不奉陪,我只爲小王,嘿嘿。

     先來說說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報頭
ICMP報頭
ICMP數據報

     由於IP層協議是一種點對點的協議,而非端對端的協議,它提供無連接的數據報服務,沒有端口的概念,因此很少使用bind()和connect() 函數,若有使用也只是用於設置IP地址。發送數據使用sendto()函數,接收數據使用recvfrom()函數。

     TCP/IP的經典大作《TCP/IP協議詳解.卷一》清晰的告訴我,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報文格式如下:

    ICMP

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

#define ICMP_ECHO   0
#define ICMP_ECHOREPLY 8

    在Linux中ICMP數據結構(<netinet/ip_icmp.h>)定義如下:

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)。結果告訴我,小王微微的笑了(調皮的很,還不想讓我看見),我也就開心了..

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章