linux下ping的C语言实现(转)
1 #include 2 #include 3 #include 4 #include 5 #include 6 #include 7 #include in.h> 8 #include 9 #include 10 #include 11 #include 12 #include
13 #define PACKET_SIZE 4096 14 #define MAX_WAIT_TIME 5 15 #define MAX_NO_PACKETS 3 16 char sendpacket[PACKET_SIZE]; 17 char recvpacket[PACKET_SIZE]; 18 int sockfd,datalen=56; 19 int nsend=0,nreceived=0; 20 struct sockaddr_in dest_addr;
21 pid_t pid;
22 struct sockaddr_in from; 23 struct timeval tvrecv; 24 void statistics(int signo);
25 unsigned short cal_chksum(unsigned short *addr,int len);
26 int pack(int pack_no); 27 void send_packet(void); 28 void recv_packet(void); 29 int unpack(char *buf,int len);
30 void tv_sub(struct timeval *out,struct timeval *in); 31 void statistics(int signo) 32 {
33 printf(\statistics-------------------\\n\
34 printf(\received , %%%d
lost\\n\ 35 close(sockfd); 36 exit(1); 37 }
38 /*校验和算法*/
39 unsigned short cal_chksum(unsigned short *addr,int len)
40 { 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;