自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Linux編程之PING的實現(xiàn)

系統(tǒng) Linux
PING(Packet InterNet Groper)中文名為因特網(wǎng)包探索器,是用來查看網(wǎng)絡(luò)上另一個主機系統(tǒng)的網(wǎng)絡(luò)連接是否正常的一個工具。ping命令的工作原理是:向網(wǎng)絡(luò)上的另一個主機系統(tǒng)發(fā)送ICMP報文,如果指定系統(tǒng)得到了報文,它將把回復(fù)報文傳回給發(fā)送者,這有點象潛水艇聲納系統(tǒng)中使用的發(fā)聲裝置。

PING(Packet InterNet Groper)中文名為因特網(wǎng)包探索器,是用來查看網(wǎng)絡(luò)上另一個主機系統(tǒng)的網(wǎng)絡(luò)連接是否正常的一個工具。ping命令的工作原理是:向網(wǎng)絡(luò)上的另一個主機系統(tǒng)發(fā)送ICMP報文,如果指定系統(tǒng)得到了報文,它將把回復(fù)報文傳回給發(fā)送者,這有點象潛水艇聲納系統(tǒng)中使用的發(fā)聲裝置。所以,我們想知道我這臺主機能不能和另一臺進(jìn)行通信,我們首先需要確認(rèn)的是我們兩臺主機間的網(wǎng)絡(luò)是不是通的,也就是我說的話能不能傳到你那里,這是雙方進(jìn)行通信的前提。在Linux下使用指令ping的方法和現(xiàn)象如下: 

 

 

在Linux下使用指令ping的方法和現(xiàn)象 

PING的實現(xiàn)看起來并不復(fù)雜,我想自己寫代碼實現(xiàn)這個功能,需要些什么知識儲備?我簡單羅列了一下:

  • ICMP協(xié)議的理解
  • RAW套接字
  • 網(wǎng)絡(luò)封包和解包技能

搭建這么一個ping程序的步驟如下:

  1. ICMP包的封裝和解封
  2. 創(chuàng)建一個線程用于ICMP包的發(fā)送
  3. 創(chuàng)建一個線程用于ICMP包的接收
  4. 原始套接字編程

PING的流程如下: 

 

 

 

一、ICMP包的封裝和解封

(1) ICMP協(xié)議理解

要進(jìn)行PING的開發(fā),我們首先需要知道PING的實現(xiàn)是基于ICMP協(xié)議來開發(fā)的。要進(jìn)行ICMP包的封裝和解封,我們首先需要理解ICMP協(xié)議。ICMP位于網(wǎng)絡(luò)層,允許主機或者路由器報告差錯情況和提供有關(guān)異常情況的報告。ICMP報文是封裝在IP數(shù)據(jù)報中,作為其中的數(shù)據(jù)部分。ICMP報文作為IP層數(shù)據(jù)報的數(shù)據(jù),加上數(shù)據(jù)報頭,組成IP數(shù)據(jù)報發(fā)送出去。ICMP報文格式如下: 

 

 

 

ICMP報文的種類有兩種,即ICMP差錯報告報文和ICMP詢問報文。PING程序使用的ICMP報文種類為ICMP詢問報文。注意一下上面說到的ICMP報文格式中的“類型”字段,我們在組包的時候可以向該字段填寫不同的值來標(biāo)定該ICMP報文的類型。下面列出的是幾種常用的ICMP報文類型。 

 

 

 

我們的PING程序需要用到的ICMP的類型是回送請求(8)。

因為ICMP報文的具體格式會因為ICMP報文的類型而各不相同,我們ping包的格式是這樣的: 

 

 

 

(2) ICMP包的組裝

對照上面的ping包格式,我們封裝ping包的代碼可以這么寫:

  1. void icmp_pack(struct icmp* icmphdr, int seq, int length) 
  2. {    int i = 0; 
  3.  
  4.     icmphdr->icmp_type = ICMP_ECHO;  //類型填回送請求 
  5.     icmphdr->icmp_code = 0;    
  6.     icmphdr->icmp_cksum = 0; //注意,這里先填寫0,很重要! 
  7.     icmphdr->icmp_seq = seq;  //這里的序列號我們填1,2,3,4.... 
  8.     icmphdr->icmp_id = pid & 0xffff;  //我們使用pid作為icmp_id,icmp_id只是2字節(jié),而pid有4字節(jié) 
  9.     for(i=0;i<length;i++) 
  10.     { 
  11.         icmphdr->icmp_data[i] = i;  //填充數(shù)據(jù)段,使ICMP報文大于64B    } 
  12.  
  13.     icmphdr->icmp_cksum = cal_chksum((unsigned short*)icmphdr, length); //校驗和計算}  

這里再三提醒一下,icmp_cksum 必須先填寫為0再執(zhí)行校驗和算法計算,否則ping時對方主機會因為校驗和計算錯誤而丟棄請求包,導(dǎo)致ping的失敗。我一個同事曾經(jīng)就因為這么一個錯誤而排查許久,血的教訓(xùn)請銘記。

這里簡單介紹一下checksum(校驗和)。

計算機網(wǎng)絡(luò)通信時,為了檢驗在數(shù)據(jù)傳輸過程中數(shù)據(jù)是否發(fā)生了錯誤,通常在傳輸數(shù)據(jù)的時候連同校驗和一塊傳輸,當(dāng)接收端接受數(shù)據(jù)時候會從新計算校驗和,如果與原校驗和不同就視為出錯,丟棄該數(shù)據(jù)包,并返回icmp報文。

算法基本思路:

IP/ICMP/IGMP/TCP/UDP等協(xié)議的校驗和算法都是相同的,采用的都是將數(shù)據(jù)流視為16位整數(shù)流進(jìn)行重復(fù)疊加計算。為了計算檢驗和,首先把檢驗和字段置為0。然后,對有效數(shù)據(jù)范圍內(nèi)中每個16位進(jìn)行二進(jìn)制反碼求和,結(jié)果存在檢驗和字段中,如果數(shù)據(jù)長度為奇數(shù)則補一字節(jié)0。當(dāng)收到數(shù)據(jù)后,同樣對有效數(shù)據(jù)范圍中每個16位數(shù)進(jìn)行二進(jìn)制反碼的求和。由于接收方在計算過程中包含了發(fā)送方存在首部中的檢驗和,因此,如果首部在傳輸過程中沒有發(fā)生任何差錯,那么接收方計算的結(jié)果應(yīng)該為全0或全1(具體看實現(xiàn)了,本質(zhì)一樣) 。如果結(jié)果不是全0或全1,那么表示數(shù)據(jù)錯誤。 

  1. /*校驗和算法*/ 
  2.  
  3. unsigned short cal_chksum(unsigned short *addr,int len) 
  4. {       int nleft=len;        int sum=0; 
  5.         unsigned short *w=addr; 
  6.         unsigned short answer=0;        /*把ICMP報頭二進(jìn)制數(shù)據(jù)以2字節(jié)為單位累加起來*/ 
  7.         while(nleft>1) 
  8.         {        
  9.             sum+=*w++; 
  10.             nleft-=2; 
  11.         }        /*若ICMP報頭為奇數(shù)個字節(jié),會剩下***一字節(jié)。把***一個字節(jié)視為一個2字節(jié)數(shù)據(jù)的高字節(jié),這個2字節(jié)數(shù)據(jù)的低字節(jié)為0,繼續(xù)累加*/ 
  12.         if( nleft==1) 
  13.         {        
  14.             *(unsigned char *)(&answer)=*(unsigned char *)w; 
  15.             sum+=answer; 
  16.         } 
  17.         sum=(sum>>16)+(sum&0xffff); 
  18.         sum+=(sum>>16); 
  19.         answer=~sum;        return answer; 
  20.  

(3) ICMP包的解包

知道怎么封裝包,那解包就也不難了,注意的是,收到一個ICMP包,我們不要就認(rèn)為這個包就是我們發(fā)出去的ICMP回送回答包,我們需要加一層代碼來判斷該ICMP報文的id和seq字段是否符合我們發(fā)送的ICMP報文的設(shè)置,來驗證ICMP回復(fù)包的正確性。

  1. int icmp_unpack(char* buf, int len) 
  2. {    int iphdr_len;    struct timeval begin_time, recv_time, offset_time;    int rtt;  //round trip time 
  3.  
  4.     struct ip* ip_hdr = (struct ip *)buf; 
  5.     iphdr_len = ip_hdr->ip_hl*4;    struct icmp* icmp = (struct icmp*)(buf+iphdr_len); //使指針跳過IP頭指向ICMP頭 
  6.     len-=iphdr_len;  //icmp包長度 
  7.     if(len < 8)   //判斷長度是否為ICMP包長度    { 
  8.         fprintf(stderr, "Invalid icmp packet.Its length is less than 8\n");        return -1; 
  9.     }    //判斷該包是ICMP回送回答包且該包是我們發(fā)出去的 
  10.     if((icmp->icmp_type == ICMP_ECHOREPLY) && (icmp->icmp_id == (pid & 0xffff)))  
  11.     {        if((icmp->icmp_seq < 0) || (icmp->icmp_seq > PACKET_SEND_MAX_NUM)) 
  12.         { 
  13.             fprintf(stderr, "icmp packet seq is out of range!\n");            return -1; 
  14.         } 
  15.  
  16.         ping_packet[icmp->icmp_seq].flag = 0; 
  17.         begin_time = ping_packet[icmp->icmp_seq].begin_time;  //去除該包的發(fā)出時間 
  18.         gettimeofday(&recv_time, NULL); 
  19.  
  20.         offset_time = cal_time_offset(begin_time, recv_time); 
  21.         rtt = offset_time.tv_sec*1000 + offset_time.tv_usec/1000; //毫秒為單位 
  22.         printf("%d byte from %s: icmp_seq=%u ttl=%d rtt=%d ms\n"
  23.             len, inet_ntoa(ip_hdr->ip_src), icmp->icmp_seq, ip_hdr->ip_ttl, rtt);         
  24.  
  25.     }    else 
  26.     { 
  27.         fprintf(stderr, "Invalid ICMP packet! Its id is not matched!\n");        return -1; 
  28.     }    return 0; 
  29.  

二、發(fā)包線程的搭建

根據(jù)PING程序的框架,我們需要建立一個線程用于ping包的發(fā)送,我的想法是這樣的:使用sendto進(jìn)行發(fā)包,發(fā)包速率我們維持在1秒1發(fā),我們需要用一個全局變量記錄***個ping包發(fā)出的時間,除此之外,我們還需要一個全局變量來記錄我們發(fā)出的ping包到底有幾個,這兩個變量用于后來收到ping包回復(fù)后的數(shù)據(jù)計算。

  1. void ping_send() 
  2. {    char send_buf[128]; 
  3.     memset(send_buf, 0, sizeof(send_buf)); 
  4.     gettimeofday(&start_time, NULL); //記錄***個ping包發(fā)出的時間 
  5.     while(alive) 
  6.     {        int size = 0; 
  7.         gettimeofday(&(ping_packet[send_count].begin_time), NULL); 
  8.         ping_packet[send_count].flag = 1; //將該標(biāo)記為設(shè)置為該包已發(fā)送 
  9.         icmp_pack((struct icmp*)send_buf, send_count, 64); //封裝icmp包 
  10.         size = sendto(rawsock, send_buf, 64, 0, (struct sockaddr*)&dest, sizeof(dest)); 
  11.         send_count++; //記錄發(fā)出ping包的數(shù)量 
  12.         if(size < 0) 
  13.         { 
  14.             fprintf(stderr, "send icmp packet fail!\n");            continue
  15.         } 
  16.  
  17.         sleep(1); 
  18.     } 
  19.  

三、收包線程的搭建

我們同樣建立一個接收包的線程,這里我們采用select函數(shù)進(jìn)行收包,并為select函數(shù)設(shè)置超時時間為200us,若發(fā)生超時,則進(jìn)行下一個循環(huán)。同樣地,我們也需要一個全局變量來記錄成功接收到的ping回復(fù)包的數(shù)量。

  1. void ping_recv() 
  2. {    struct timeval tv; 
  3.     tv.tv_usec = 200;  //設(shè)置select函數(shù)的超時時間為200us 
  4.     tv.tv_sec = 0; 
  5.     fd_set read_fd;    char recv_buf[512]; 
  6.     memset(recv_buf, 0 ,sizeof(recv_buf));    while(alive) 
  7.     {        int ret = 0; 
  8.         FD_ZERO(&read_fd); 
  9.         FD_SET(rawsock, &read_fd); 
  10.         ret = select(rawsock+1, &read_fd, NULLNULL, &tv);        switch(ret) 
  11.         {            case -1: 
  12.                 fprintf(stderr,"fail to select!\n");                break;            case 0:                break;            default
  13.                 {                    int size = recv(rawsock, recv_buf, sizeof(recv_buf), 0);                    if(size < 0) 
  14.                     { 
  15.                         fprintf(stderr,"recv data fail!\n");                        continue
  16.                     } 
  17.  
  18.                     ret = icmp_unpack(recv_buf, size); //對接收的包進(jìn)行解封 
  19.                     if(ret == -1)  //不是屬于自己的icmp包,丟棄不處理                    {                        continue
  20.                     } 
  21.                     recv_count++; //接收包計數(shù)                }                break; 
  22.         } 
  23.  
  24.     } 
  25.  

四、中斷處理

我們規(guī)定了一次ping發(fā)送的包的***值為64個,若超出該數(shù)值就停止發(fā)送。作為PING的使用者,我們一般只會發(fā)送若干個包,若有這幾個包順利返回,我們就crtl+c中斷ping。這里的代碼主要是為中斷信號寫一個中斷處理函數(shù),將alive這個全局變量設(shè)置為0,進(jìn)而使發(fā)送ping包的循環(huán)停止而結(jié)束程序。

  1. oid icmp_sigint(int signo) 
  2.     alive = 0; 
  3.     gettimeofday(&end_time, NULL); 
  4.     time_interval = cal_time_offset(start_time, end_time); 
  5.  
  6. signal(SIGINT, icmp_sigint);  

五、總體實現(xiàn)

各模塊介紹完了,現(xiàn)在貼出完整代碼。 

  1. #include <stdio.h>   
  2. #include <netinet/in.h>   
  3. #include <netinet/ip.h>   
  4. #include <netinet/ip_icmp.h>   
  5. #include <unistd.h>   
  6. #include <signal.h>   
  7. #include <arpa/inet.h>   
  8. #include <errno.h>   
  9. #include <sys/time.h>  
  10. #include <string.h>  
  11. #include <netdb.h>  
  12. #include <pthread.h>  
  13.    
  14.    
  15. #define PACKET_SEND_MAX_NUM 64  
  16.     
  17.  typedef struct ping_packet_status  
  18.  {  
  19.       struct timeval begin_time;  
  20.       struct timeval end_time;  
  21.       int flag;   //發(fā)送標(biāo)志,1為已發(fā)送  
  22.       int seq;     //包的序列號  
  23.   }ping_packet_status;  
  24.     
  25.     
  26.     
  27.   ping_packet_status ping_packet[PACKET_SEND_MAX_NUM];  
  28.     
  29.   int alive;  
  30.   int rawsock;  
  31.   int send_count;  
  32.   int recv_count;  
  33.   pid_t pid;  
  34.   struct sockaddr_in dest;  
  35.   struct timeval start_time;  
  36.   struct timeval end_time;  
  37.   struct timeval time_interval;  
  38.     
  39.   /*校驗和算法*/  
  40.   unsigned short cal_chksum(unsigned short *addr,int len) {       int nleft=len;  
  41.           int sum=0;  
  42.           unsigned short *w=addr;  
  43.           unsigned short answer=0;  
  44.     
  45.           /*把ICMP報頭二進(jìn)制數(shù)據(jù)以2字節(jié)為單位累加起來*/  
  46.           while(nleft>1)  
  47.           {        
  48.               sum+=*w++;  
  49.               nleft-=2;  
  50.           }  
  51.           /*若ICMP報頭為奇數(shù)個字節(jié),會剩下***一字節(jié)。把***一個字節(jié)視為一個2字節(jié)數(shù)據(jù)的高字節(jié),這個2字節(jié)數(shù)據(jù)的低字節(jié)為0,繼續(xù)累加*/  
  52.           if( nleft==1)  
  53.           {        
  54.               *(unsigned char *)(&answer)=*(unsigned char *)w;  
  55.               sum+=answer;  
  56.           }  
  57.           sum=(sum>>16)+(sum&0xffff);  
  58.           sum+=(sum>>16);  
  59.           answer=~sum;  
  60.           return answer;  
  61.   }  
  62.     
  63.   struct timeval cal_time_offset(struct timeval begin, struct timeval end)  
  64.   {  
  65.       struct timeval ans;  
  66.       ans.tv_sec = end.tv_sec - begin.tv_sec;  
  67.       ans.tv_usec = end.tv_usec - begin.tv_usec;  
  68.       if(ans.tv_usec < 0) //如果接收時間的usec小于發(fā)送時間的usec,則向sec域借位  
  69.       {  
  70.           ans.tv_sec--;  
  71.           ans.tv_usec+=1000000;  
  72.       }  
  73.       return ans;  
  74.   }  
  75.     
  76.   void icmp_pack(struct icmp* icmphdr, int seq, int length)  
  77.   {  
  78.       int i = 0;  
  79.     
  80.       icmphdr->icmp_type = ICMP_ECHO;  
  81.       icmphdr->icmp_code = 0;  
  82.       icmphdr->icmp_cksum = 0;  
  83.       icmphdr->icmp_seq = seq;  
  84.       icmphdr->icmp_id = pid & 0xffff;  
  85.       for(i=0;i<length;i++)  
  86.       {  
  87.           icmphdr->icmp_data[i] = i;  
  88.       }  
  89.     
  90.       icmphdr->icmp_cksum = cal_chksum((unsigned short*)icmphdr, length);  
  91.   }  
  92.     
  93.   int icmp_unpack(char* buf, int len)  
  94.   {  
  95.       int iphdr_len;  
  96.       struct timeval begin_time, recv_time, offset_time;  
  97.       int rtt;  //round trip time  
  98.    
  99.      struct ip* ip_hdr = (struct ip *)buf; 
  100.      iphdr_len = ip_hdr->ip_hl*4; 
  101.  
  102.      struct icmp* icmp = (struct icmp*)(buf+iphdr_len); 
  103.      len-=iphdr_len;  //icmp包長度 
  104.      if(len < 8)   //判斷長度是否為ICMP包長度 
  105.      { 
  106.          fprintf(stderr, "Invalid icmp packet.Its length is less than 8\n"); 
  107.          return -1; 
  108.      }   
  109.   
  110.      //判斷該包是ICMP回送回答包且該包是我們發(fā)出去的 
  111.      if((icmp->icmp_type == ICMP_ECHOREPLY) && (icmp->icmp_id == (pid & 0xffff)))  
  112.      { 
  113.          if((icmp->icmp_seq < 0) || (icmp->icmp_seq > PACKET_SEND_MAX_NUM)) 
  114.   
  115.          { 
  116.          
  117.              fprintf(stderr, "icmp packet seq is out of range!\n"); 
  118.              return -1; 
  119.          } 
  120.   
  121.          ping_packet[icmp->icmp_seq].flag = 0; 
  122.          begin_time = ping_packet[icmp->icmp_seq].begin_time; 
  123.          gettimeofday(&recv_time, NULL); 
  124.   
  125.          offset_time = cal_time_offset(begin_time, recv_time); 
  126.          rtt = offset_time.tv_sec*1000 + offset_time.tv_usec/1000; //毫秒為單位 
  127.   
  128.          printf("%d byte from %s: icmp_seq=%u ttl=%d rtt=%d ms\n"
  129.              len, inet_ntoa(ip_hdr->ip_src), icmp->icmp_seq, ip_hdr->ip_ttl, rtt);         
  130.   
  131.      } 
  132.      else 
  133.      { 
  134.          fprintf(stderr, "Invalid ICMP packet! Its id is not matched!\n"); 
  135.          return -1; 
  136.      } 
  137.      return 0; 
  138.  } 
  139.   
  140.  void ping_send() 
  141.  { 
  142.      char send_buf[128]; 
  143.      memset(send_buf, 0, sizeof(send_buf)); 
  144.      gettimeofday(&start_time, NULL); //記錄***個ping包發(fā)出的時間 
  145.      while(alive) 
  146.      { 
  147.          int size = 0; 
  148.          gettimeofday(&(ping_packet[send_count].begin_time), NULL); 
  149.          ping_packet[send_count].flag = 1; //將該標(biāo)記為設(shè)置為該包已發(fā)送 
  150.   
  151.          icmp_pack((struct icmp*)send_buf, send_count, 64); //封裝icmp包 
  152.          size = sendto(rawsock, send_buf, 64, 0, (struct sockaddr*)&dest, sizeof(dest)); 
  153.          send_count++; //記錄發(fā)出ping包的數(shù)量 
  154.          if(size < 0) 
  155.          { 
  156.              fprintf(stderr, "send icmp packet fail!\n"); 
  157.              continue
  158.          } 
  159.   
  160.          sleep(1); 
  161.      } 
  162.  } 
  163.   
  164.  void ping_recv() 
  165.  {     struct timeval tv; 
  166.      tv.tv_usec = 200;  //設(shè)置select函數(shù)的超時時間為200us 
  167.      tv.tv_sec = 0; 
  168.      fd_set read_fd; 
  169.      char recv_buf[512]; 
  170.      memset(recv_buf, 0 ,sizeof(recv_buf)); 
  171.      while(alive) 
  172.      { 
  173.          int ret = 0; 
  174.          FD_ZERO(&read_fd); 
  175.          FD_SET(rawsock, &read_fd); 
  176.          ret = select(rawsock+1, &read_fd, NULLNULL, &tv); 
  177.          switch(ret) 
  178.          { 
  179.              case -1: 
  180.                  fprintf(stderr,"fail to select!\n"); 
  181.                 break; 
  182.              case 0: 
  183.                  break; 
  184.              default
  185.                  { 
  186.                      int size = recv(rawsock, recv_buf, sizeof(recv_buf), 0); 
  187.                      if(size < 0) 
  188.                      { 
  189.                          fprintf(stderr,"recv data fail!\n"); 
  190.                          continue
  191.                      } 
  192.   
  193.                     ret = icmp_unpack(recv_buf, size); //對接收的包進(jìn)行解封 
  194.                      if(ret == -1)  //不是屬于自己的icmp包,丟棄不處理 
  195.                      { 
  196.                          continue
  197.                      } 
  198.                      recv_count++; //接收包計數(shù) 
  199.                  } 
  200.                  break; 
  201.          } 
  202.   
  203.      }    
  204.  } 
  205.   
  206.  void icmp_sigint(int signo) 
  207.  { 
  208.      alive = 0; 
  209.      gettimeofday(&end_time, NULL); 
  210.      time_interval = cal_time_offset(start_time, end_time); 
  211.  } 
  212.   
  213.  void ping_stats_show()  
  214.  { 
  215.      long time = time_interval.tv_sec*1000+time_interval.tv_usec/1000; 
  216.      /*注意除數(shù)不能為零,這里send_count有可能為零,所以運行時提示錯誤*/ 
  217.      printf("%d packets transmitted, %d recieved, %d%c packet loss, time %ldms\n"
  218.          send_count, recv_count, (send_count-recv_count)*100/send_count, '%'time); 
  219.  
  220.  
  221. int main(int argc, char* argv[]) 
  222. int size = 128*1024;//128k 
  223. struct protoent* protocol = NULL
  224. char dest_addr_str[80]; 
  225. memset(dest_addr_str, 0, 80); 
  226. unsigned int inaddr = 1; 
  227. struct hostent* host = NULL
  228.  
  229. pthread_t send_id,recv_id;   
  230.   
  231. if(argc < 2) 
  232. {   
  233. printf("Invalid IP ADDRESS!\n"); 
  234.          return -1; 
  235.   }    
  236.   
  237.   protocol = getprotobyname("icmp"); //獲取協(xié)議類型ICMP 
  238. if(protocol == NULL
  239.   {   
  240.   printf("Fail to getprotobyname!\n"); 
  241.       return -1; 
  242.   }     
  243.   
  244.   memcpy(dest_addr_str, argv[1], strlen(argv[1])+1); 
  245.  
  246.   rawsock = socket(AF_INET,SOCK_RAW,protocol->p_proto); 
  247.   if(rawsock < 0) 
  248.   {    
  249.      printf("Fail to create socket!\n"); 
  250.    return -1; 
  251.   }   
  252.  
  253.   pid = getpid(); 
  254.  
  255.   setsockopt(rawsock, SOL_SOCKET, SO_RCVBUF, &size, sizeof(size)); //增大接收緩沖區(qū)至128K 
  256.   
  257.   bzero(&dest,sizeof(dest)); 
  258.  
  259.  dest.sin_family = AF_INET; 
  260.  
  261.  inaddr = inet_addr(argv[1]); 
  262.  if(inaddr == INADDR_NONE)   //判斷用戶輸入的是否為IP地址還是域名 
  263.  {   
  264.          //輸入的是域名地址 
  265.          host = gethostbyname(argv[1]); 
  266.          if(host == NULL
  267.          {     
  268.              printf("Fail to gethostbyname!\n"); 
  269.              return -1; 
  270.          }        
  271.   
  272.          memcpy((char*)&dest.sin_addr, host->h_addr, host->h_length); 
  273.      }  
  274.      else 
  275.      { 
  276.          memcpy((char*)&dest.sin_addr, &inaddr, sizeof(inaddr));//輸入的是IP地址 
  277.      } 
  278.      inaddr = dest.sin_addr.s_addr; 
  279.      printf("PING %s, (%d.%d.%d.%d) 56(84) bytes of data.\n",dest_addr_str, 
  280.          (inaddr&0x000000ff), (inaddr&0x0000ff00)>>8,  
  281.          (inaddr&0x00ff0000)>>16, (inaddr&0xff000000)>>24); 
  282.   
  283.      alive = 1;  //控制ping的發(fā)送和接收 
  284.   
  285.      signal(SIGINT, icmp_sigint); 
  286.  
  287.      if(pthread_create(&send_id, NULL, (void*)ping_send, NULL)) 
  288.      {   
  289.          printf("Fail to create ping send thread!\n"); 
  290.          return -1; 
  291.      }  
  292.   
  293.      if(pthread_create(&recv_id, NULL, (void*)ping_recv, NULL)) 
  294.      { 
  295.          printf("Fail to create ping recv thread!\n"); 
  296.          return -1; 
  297.      }   
  298.   
  299.      pthread_join(send_id, NULL);//等待send ping線程結(jié)束后進(jìn)程再結(jié)束 
  300.      pthread_join(recv_id, NULL);//等待recv ping線程結(jié)束后進(jìn)程再結(jié)束 
  301.   
  302.      ping_stats_show();  
  303.   
  304.      close(rawsock);    
  305.      return 0; 
  306.   
  307.  }  

編譯以及實驗現(xiàn)象如下:

我的實驗環(huán)境是兩臺服務(wù)器,發(fā)起ping的主機是172.0.5.183,被ping的主機是172.0.5.182,以下是我的兩次實驗現(xiàn)象(ping IP和ping 域名)。

特別注意:

只有root用戶才能利用socket()函數(shù)生成原始套接字,要讓Linux的一般用戶能執(zhí)行以上程序,需進(jìn)行如下的特別操作:用root登陸,編譯以上程序gcc -lpthread -o ping ping.c 

 

 

 

實驗現(xiàn)象可以看出,PING是成功的,表明兩主機間的網(wǎng)絡(luò)是通的,發(fā)出的所有ping包都收到了回復(fù)。

下面是Linux系統(tǒng)自帶的PING程序,我們可以對比一下我們設(shè)計的PING程序跟系統(tǒng)自帶的PING程序有何不同。 

 

責(zé)任編輯:龐桂玉 來源: 嵌入式Linux中文站
相關(guān)推薦

2010-08-02 14:29:46

LinuxPingICMP

2011-05-27 15:56:30

Android

2017-01-15 15:20:47

Linux編程log

2020-11-06 18:51:17

LinuxTCP服務(wù)器

2015-03-20 09:54:44

網(wǎng)絡(luò)編程面向連接無連接

2012-10-29 13:25:54

JavaScriptJSjQuery

2009-08-17 09:50:59

C# ping命令

2015-04-24 09:48:59

TCPsocketsocket編程

2009-07-27 14:29:31

ASP.NET編程彈窗報警提示

2022-02-14 15:07:48

進(jìn)程FileChanne線程

2013-06-07 16:30:08

iOS多線程iOS開發(fā)NSThread

2011-07-21 10:17:53

java

2009-09-28 11:21:17

Linux教程ls命令Linux

2009-09-25 10:06:37

Linux教程Linux pwdLinux命令

2015-05-08 09:57:59

綁定端口端口復(fù)用網(wǎng)絡(luò)編程

2009-09-25 10:08:24

Linux教程Linux cdLinux命令

2009-09-28 11:19:45

Linux教程dir命令Linux

2013-06-08 14:37:20

編程軟件

2011-06-01 14:53:17

比爾-蓋茨

2011-11-16 13:22:38

Jscex
點贊
收藏

51CTO技術(shù)棧公眾號