標籤:資料 argv 最大 return name clu gettime signed loss
void icmp_pack(struct icmp* icmphdr, int seq, int length){ int i = 0; icmphdr->icmp_type = ICMP_ECHO; //類型填回送請求 icmphdr->icmp_code = 0; icmphdr->icmp_cksum = 0; //注意,這裡先填寫0,很重要! icmphdr->icmp_seq = seq; //這裡的序號我們填1,2,3,4.... icmphdr->icmp_id = pid & 0xffff; //我們使用pid作為icmp_id,icmp_id只是2位元組,而pid有4位元組 for(i=0;i<length;i++) { icmphdr->icmp_data[i] = i; //填充資料區段,使ICMP報文大於64B } icmphdr->icmp_cksum = cal_chksum((unsigned short*)icmphdr, length); //校正和計算}這裡再三提醒一下,icmp_cksum 必須先填寫為0再執行校正和演算法計算,否則ping時對方主機會因為校正和計算錯誤而丟棄請求包,導致ping的失敗。我一個同事曾經就因為這麼一個錯誤而排查許久,血的教訓請銘記。
這裡簡單介紹一下checksum(校正和)。
電腦網路通訊時,為了檢驗在資料轉送過程中資料是否發生了錯誤,通常在傳輸資料的時候連同校正和一塊傳輸,當接收端接受資料時候會從新計算校正和,如果與原校正和不同就視為出錯,丟棄該資料包,並返回icmp報文。
演算法基本思路:
IP/ICMP/IGMP/TCP/UDP等協議的校正和演算法都是相同的,採用的都是將資料流視為16位整數流進行重複疊加計算。為了計算檢驗和,首先把檢驗和欄位置為0。然後,對有效資料範圍內中每個16位進行二進位反碼求和,結果存在檢驗和欄位中,如果資料長度為奇數則補一位元組0。當收到資料後,同樣對有效資料範圍中每個16位元進行二進位反碼的求和。由於接收方在計算過程中包含了發送方存在首部中的檢驗和,因此,如果首部在傳輸過程中沒有發生任何差錯,那麼接收方計算的結果應該為全0或全1(具體看實現了,本質一樣) 。如果結果不是全0或全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;}
(3) ICMP包的解包知道怎麼封裝包,那解包就也不難了,注意的是,收到一個ICMP包,我們不要就認為這個包就是我們發出去的ICMP回送回答包,我們需要加一層代碼來判斷該ICMP報文的id和seq欄位是否符合我們發送的ICMP報文的設定,來驗證ICMP回複包的正確性。
int icmp_unpack(char* buf, int len){ int iphdr_len; struct timeval begin_time, recv_time, offset_time; int rtt; //round trip time struct ip* ip_hdr = (struct ip *)buf; iphdr_len = ip_hdr->ip_hl*4; struct icmp* icmp = (struct icmp*)(buf+iphdr_len); //使指標跳過IP頭指向ICMP頭 len-=iphdr_len; //icmp包長度 if(len < 8) //判斷長度是否為ICMP包長度 { fprintf(stderr, "Invalid icmp packet.Its length is less than 8\n"); return -1; } //判斷該包是ICMP回送回答包且該包是我們發出去的 if((icmp->icmp_type == ICMP_ECHOREPLY) && (icmp->icmp_id == (pid & 0xffff))) { if((icmp->icmp_seq < 0) || (icmp->icmp_seq > PACKET_SEND_MAX_NUM)) { fprintf(stderr, "icmp packet seq is out of range!\n"); return -1; } ping_packet[icmp->icmp_seq].flag = 0; begin_time = ping_packet[icmp->icmp_seq].begin_time; //去除該包的發出時間 gettimeofday(&recv_time, NULL); offset_time = cal_time_offset(begin_time, recv_time); rtt = offset_time.tv_sec*1000 + offset_time.tv_usec/1000; //毫秒為單位 printf("%d byte from %s: icmp_seq=%u ttl=%d rtt=%d ms\n", len, inet_ntoa(ip_hdr->ip_src), icmp->icmp_seq, ip_hdr->ip_ttl, rtt); } else { fprintf(stderr, "Invalid ICMP packet! Its id is not matched!\n"); return -1; } return 0;}
二、發包線程的搭建根據PING程式的架構,我們需要建立一個線程用於ping包的發送,我的想法是這樣的:使用sendto進行發包,發包速率我們維持在1秒1發,我們需要用一個全域變數記錄第一個ping包發出的時間,除此之外,我們還需要一個全域變數來記錄我們發出的ping包到底有幾個,這兩個變數用於後來收到ping包回複後的資料計算。
void ping_send(){ char send_buf[128]; memset(send_buf, 0, sizeof(send_buf)); gettimeofday(&start_time, NULL); //記錄第一個ping包發出的時間 while(alive) { int size = 0; gettimeofday(&(ping_packet[send_count].begin_time), NULL); ping_packet[send_count].flag = 1; //將該標記為設定為該包已發送 icmp_pack((struct icmp*)send_buf, send_count, 64); //封裝icmp包 size = sendto(rawsock, send_buf, 64, 0, (struct sockaddr*)&dest, sizeof(dest)); send_count++; //記錄發出ping包的數量 if(size < 0) { fprintf(stderr, "send icmp packet fail!\n"); continue; } sleep(1); }}
三、收包線程的搭建
我們同樣建立一個接收包的線程,這裡我們採用select函數進行收包,並為select函數設定逾時時間為200us,若發生逾時,則進行下一個迴圈。同樣地,我們也需要一個全域變數來記錄成功接收到的ping回複包的數量。
void ping_recv(){ struct timeval tv; tv.tv_usec = 200; //設定select函數的逾時時間為200us tv.tv_sec = 0; fd_set read_fd; char recv_buf[512]; memset(recv_buf, 0 ,sizeof(recv_buf)); while(alive) { int ret = 0; FD_ZERO(&read_fd); FD_SET(rawsock, &read_fd); ret = select(rawsock+1, &read_fd, NULL, NULL, &tv); switch(ret) { case -1: fprintf(stderr,"fail to select!\n"); break; case 0: break; default: { int size = recv(rawsock, recv_buf, sizeof(recv_buf), 0); if(size < 0) { fprintf(stderr,"recv data fail!\n"); continue; } ret = icmp_unpack(recv_buf, size); //對接收的包進行解鎖 if(ret == -1) //不是屬於自己的icmp包,丟棄不處理 { continue; } recv_count++; //接收包計數 } break; } }}
四、中斷處理我們規定了一次ping發送的包的最大值為64個,若超出該數值就停止發送。作為PING的使用者,我們一般只會發送若干個包,若有這幾個包順利返回,我們就crtl+c中斷ping。這裡的代碼主要是為中斷訊號寫一個中斷處理函數,將alive這個全域變數設定為0,進而使發送ping包的迴圈停止而結束程式。
void icmp_sigint(int signo){ alive = 0; gettimeofday(&end_time, NULL); time_interval = cal_time_offset(start_time, end_time);}signal(SIGINT, icmp_sigint);
五、總體實現各模組介紹完了,現在貼出完整代碼。
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; //發送標誌,1為已發送 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) 41 { int nleft=len; 42 int sum=0; 43 unsigned short *w=addr; 44 unsigned short answer=0; 45 46 /*把ICMP前序位元據以2位元組為單位累加起來*/ 47 while(nleft>1) 48 { 49 sum+=*w++; 50 nleft-=2; 51 } 52 /*若ICMP前序為奇數個位元組,會剩下最後一位元組。把最後一個位元組視為一個2位元組資料的高位元組,這個2位元組資料的低位元組為0,繼續累加*/ 53 if( nleft==1) 54 { 55 *(unsigned char *)(&answer)=*(unsigned char *)w; 56 sum+=answer; 57 } 58 sum=(sum>>16)+(sum&0xffff); 59 sum+=(sum>>16); 60 answer=~sum; 61 return answer; 62 } 63 64 struct timeval cal_time_offset(struct timeval begin, struct timeval end) 65 { 66 struct timeval ans; 67 ans.tv_sec = end.tv_sec - begin.tv_sec; 68 ans.tv_usec = end.tv_usec - begin.tv_usec; 69 if(ans.tv_usec < 0) //如果接收時間的usec小於發送時間的usec,則向sec域借位 70 { 71 ans.tv_sec--; 72 ans.tv_usec+=1000000; 73 } 74 return ans; 75 } 76 77 void icmp_pack(struct icmp* icmphdr, int seq, int length) 78 { 79 int i = 0; 80 81 icmphdr->icmp_type = ICMP_ECHO; 82 icmphdr->icmp_code = 0; 83 icmphdr->icmp_cksum = 0; 84 icmphdr->icmp_seq = seq; 85 icmphdr->icmp_id = pid & 0xffff; 86 for(i=0;i<length;i++) 87 { 88 icmphdr->icmp_data[i] = i; 89 } 90 91 icmphdr->icmp_cksum = cal_chksum((unsigned short*)icmphdr, length); 92 } 93 94 int icmp_unpack(char* buf, int len) 95 { 96 int iphdr_len; 97 struct timeval begin_time, recv_time, offset_time; 98 int rtt; //round trip time 99 100 struct ip* ip_hdr = (struct ip *)buf;101 iphdr_len = ip_hdr->ip_hl*4;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回送回答包且該包是我們發出去的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 fprintf(stderr, "icmp packet seq is out of range!\n");116 return -1;117 }118 119 ping_packet[icmp->icmp_seq].flag = 0;120 begin_time = ping_packet[icmp->icmp_seq].begin_time;121 gettimeofday(&recv_time, NULL);122 123 offset_time = cal_time_offset(begin_time, recv_time);124 rtt = offset_time.tv_sec*1000 + offset_time.tv_usec/1000; //毫秒為單位125 126 printf("%d byte from %s: icmp_seq=%u ttl=%d rtt=%d ms\n",127 len, inet_ntoa(ip_hdr->ip_src), icmp->icmp_seq, ip_hdr->ip_ttl, rtt); 128 129 }130 else131 {132 fprintf(stderr, "Invalid ICMP packet! Its id is not matched!\n");133 return -1;134 }135 return 0;136 }137 138 void ping_send()139 {140 char send_buf[128];141 memset(send_buf, 0, sizeof(send_buf));142 gettimeofday(&start_time, NULL); //記錄第一個ping包發出的時間143 while(alive)144 {145 int size = 0;146 gettimeofday(&(ping_packet[send_count].begin_time), NULL);147 ping_packet[send_count].flag = 1; //將該標記為設定為該包已發送148 149 icmp_pack((struct icmp*)send_buf, send_count, 64); //封裝icmp包150 size = sendto(rawsock, send_buf, 64, 0, (struct sockaddr*)&dest, sizeof(dest));151 send_count++; //記錄發出ping包的數量152 if(size < 0)153 {154 fprintf(stderr, "send icmp packet fail!\n");155 continue;156 }157 158 sleep(1);159 }160 }161 162 void ping_recv()163 {164 struct timeval tv;165 tv.tv_usec = 200; //設定select函數的逾時時間為200us166 tv.tv_sec = 0;167 fd_set read_fd;168 char recv_buf[512];169 memset(recv_buf, 0 ,sizeof(recv_buf));170 while(alive)171 {172 int ret = 0;173 FD_ZERO(&read_fd);174 FD_SET(rawsock, &read_fd);175 ret = select(rawsock+1, &read_fd, NULL, NULL, &tv);176 switch(ret)177 {178 case -1:179 fprintf(stderr,"fail to select!\n");180 break;181 case 0:182 break;183 default:184 {185 int size = recv(rawsock, recv_buf, sizeof(recv_buf), 0);186 if(size < 0)187 {188 fprintf(stderr,"recv data fail!\n");189 continue;190 }191 192 ret = icmp_unpack(recv_buf, size); //對接收的包進行解鎖193 if(ret == -1) //不是屬於自己的icmp包,丟棄不處理194 {195 continue;196 }197 recv_count++; //接收包計數198 }199 break;200 }201 202 }203 }204 205 void icmp_sigint(int signo)206 {207 alive = 0;208 gettimeofday(&end_time, NULL);209 time_interval = cal_time_offset(start_time, end_time);210 }211 212 void ping_stats_show()213 {214 long time = time_interval.tv_sec*1000+time_interval.tv_usec/1000;215 /*注意除數不能為零,這裡send_count有可能為零,所以運行時提示錯誤*/216 printf("%d packets transmitted, %d recieved, %d%c packet loss, time %ldms\n",217 send_count, recv_count, (send_count-recv_count)*100/send_count, ‘%‘, time);218 }219 220 221 int main(int argc, char* argv[])222 {223 int size = 128*1024;//128k224 struct protoent* protocol = NULL;225 char dest_addr_str[80];226 memset(dest_addr_str, 0, 80);227 unsigned int inaddr = 1;228 struct hostent* host = NULL;229 230 pthread_t send_id,recv_id;231 232 if(argc < 2)233 {234 printf("Invalid IP ADDRESS!\n");235 return -1;236 }237 238 protocol = getprotobyname("icmp"); //擷取協議類型ICMP239 if(protocol == NULL)240 {241 printf("Fail to getprotobyname!\n");242 return -1;243 }244 245 memcpy(dest_addr_str, argv[1], strlen(argv[1])+1);246 247 rawsock = socket(AF_INET,SOCK_RAW,protocol->p_proto);248 if(rawsock < 0)249 {250 printf("Fail to create socket!\n");251 return -1;252 }253 254 pid = getpid();255 256 setsockopt(rawsock, SOL_SOCKET, SO_RCVBUF, &size, sizeof(size)); //增大接收緩衝區至128K257 258 bzero(&dest,sizeof(dest));259 260 dest.sin_family = AF_INET;261 262 inaddr = inet_addr(argv[1]);263 if(inaddr == INADDR_NONE) //判斷使用者輸入的是否為IP地址還是網域名稱264 {265 //輸入的是網域名稱地址266 host = gethostbyname(argv[1]);267 if(host == NULL)268 {269 printf("Fail to gethostbyname!\n");270 return -1;271 }272 273 memcpy((char*)&dest.sin_addr, host->h_addr, host->h_length);274 }275 else276 {277 memcpy((char*)&dest.sin_addr, &inaddr, sizeof(inaddr));//輸入的是IP地址278 }279 inaddr = dest.sin_addr.s_addr;280 printf("PING %s, (%d.%d.%d.%d) 56(84) bytes of data.\n",dest_addr_str,281 (inaddr&0x000000ff), (inaddr&0x0000ff00)>>8, 282 (inaddr&0x00ff0000)>>16, (inaddr&0xff000000)>>24);283 284 alive = 1; //控制ping的發送和接收285 286 signal(SIGINT, icmp_sigint);287 288 if(pthread_create(&send_id, NULL, (void*)ping_send, NULL))289 {290 printf("Fail to create ping send thread!\n");291 return -1;292 }293 294 if(pthread_create(&recv_id, NULL, (void*)ping_recv, NULL))295 {296 printf("Fail to create ping recv thread!\n");297 return -1;298 }299 300 pthread_join(send_id, NULL);//等待send ping線程結束後進程再結束301 pthread_join(recv_id, NULL);//等待recv ping線程結束後進程再結束302 303 ping_stats_show();304 305 close(rawsock);306 return 0;307 308 }編譯以及實驗現象如下:
我的實驗環境是兩台伺服器,發起ping的主機是172.0.5.183,被ping的主機是172.0.5.182,以下是我的兩次實驗現象(ping IP和ping 網域名稱)。
特別注意:
只有root使用者才能利用socket()函數產生原始通訊端,要讓Linux的一般使用者能執行以上程式,需進行如下的特別操作:用root登陸,編譯以上程式gcc -lpthread -o ping ping.c
實驗現象可以看出,PING是成功的,表明兩主機間的網路是通的,發出的所有ping包都收到了回複。下面是Linux系統內建的PING程式,我們可以對比一下我們設計的PING程式跟系統內建的PING程式有何不同。
Linux編程之PING的實現