linux下ping的C语言实现(转)

  1 #include <stdio.h>
  2 #include <signal.h>
  3 #include <arpa/inet.h>
  4 #include <sys/types.h>
  5 #include <sys/socket.h>
  6 #include <unistd.h>
  7 #include <netinet/in.h>
  8 #include <netinet/ip.h>
  9 #include <netinet/ip_icmp.h>
 10 #include <netdb.h>
 11 #include <setjmp.h>
 12 #include <errno.h>
 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("\n--------------------PING statistics-------------------\n");
 34     printf("%d packets transmitted, %d received , %%%d lost\n",nsend,nreceived,(nsend-nreceived)/nsend*100);
 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;
 57     }
 58     sum=(sum>>16)+(sum&0xffff);
 59     sum+=(sum>>16);
 60     answer=~sum;
 61     return answer;
 62 }
 63 /*设置ICMP报头*/
 64 int pack(int pack_no)
 65 {       
 66     int i,packsize;
 67     struct icmp *icmp;
 68     struct timeval *tval;
 69     icmp=(struct icmp*)sendpacket;
 70     icmp->icmp_type=ICMP_ECHO;
 71     icmp->icmp_code=0;
 72     icmp->icmp_cksum=0;
 73     icmp->icmp_seq=pack_no;
 74     icmp->icmp_id=pid;
 75     packsize=8+datalen;
 76     tval= (struct timeval *)icmp->icmp_data;
 77     gettimeofday(tval,NULL);    /*记录发送时间*/
 78     icmp->icmp_cksum=cal_chksum( (unsigned short*)icmp,packsize); /*校验算法*/
 79     return packsize;
 80 }
 81 /*发送三个ICMP报文*/
 82 void send_packet()
 83 {       
 84     int packetsize;
 85     while( nsend<MAX_NO_PACKETS)
 86     {       
 87         nsend++;
 88         packetsize=pack(nsend); /*设置ICMP报头*/
 89         if( sendto(sockfd,sendpacket,packetsize,0,(struct sockaddr *)&dest_addr,sizeof(dest_addr) )<0  )
 90         {       
 91             perror("sendto error");
 92             continue;
 93         }
 94         sleep(1); /*每隔一秒发送一个ICMP报文*/
 95     }
 96 }
 97 /*接收所有ICMP报文*/
 98 void recv_packet()
 99 {       
100     int n,fromlen;
101     extern int errno;
102     signal(SIGALRM,statistics);
103     fromlen=sizeof(from);
104     while( nreceived<nsend)
105     {       
106         alarm(MAX_WAIT_TIME);
107         if( (n=recvfrom(sockfd,recvpacket,sizeof(recvpacket),0, (struct sockaddr *)&from,&fromlen)) <0)
108        {       
109             if(errno==EINTR)
110                 continue;
111             perror("recvfrom error");
112             continue;
113        }
114        gettimeofday(&tvrecv,NULL);  /*记录接收时间*/
115        if(unpack(recvpacket,n)==-1)
116             continue;
117        nreceived++;
118     }
119 }
120 /*剥去ICMP报头*/
121 int unpack(char *buf,int len)
122 {       
123     int i,iphdrlen;
124     struct ip *ip;
125     struct icmp *icmp;
126     struct timeval *tvsend;
127     double rtt;
128     ip=(struct ip *)buf;
129     iphdrlen=ip->ip_hl<<2;    /*求ip报头长度,即ip报头的长度标志乘4*/
130     icmp=(struct icmp *)(buf+iphdrlen);  /*越过ip报头,指向ICMP报头*/
131     len-=iphdrlen;            /*ICMP报头及ICMP数据报的总长度*/
132     if( len<8)                /*小于ICMP报头长度则不合理*/
133     {       
134         printf("ICMP packets\'s length is less than 8\n");
135         return -1;
136     }
137     /*确保所接收的是我所发的的ICMP的回应*/
138     if( (icmp->icmp_type==ICMP_ECHOREPLY) && (icmp->icmp_id==pid) )
139    {       
140         tvsend=(struct timeval *)icmp->icmp_data;
141         tv_sub(&tvrecv,tvsend);  /*接收和发送的时间差*/
142         rtt=tvrecv.tv_sec*1000+tvrecv.tv_usec/1000;  /*以毫秒为单位计算rtt*/
143         /*显示相关信息*/
144         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);}
145     else    
146         return -1;
147 }
148 main(int argc,char *argv[])
149 {       
150     struct hostent *host;
151     struct protoent *protocol;
152     unsigned long inaddr=0l;
153     int waittime=MAX_WAIT_TIME;
154     int size=50*1024;
155     if(argc<2)
156     {       
157         printf("usage:%s hostname/IP address\n",argv[0]);
158         exit(1);
159     }
160     if( (protocol=getprotobyname("icmp") )==NULL)
161     {       
162         perror("getprotobyname");
163         exit(1);
164     }
165     /*生成使用ICMP的原始套接字,这种套接字只有root才能生成*/
166     if( (sockfd=socket(AF_INET,SOCK_RAW,protocol->p_proto) )<0)
167     {       
168         perror("socket error");
169         exit(1);
170     }
171     /* 回收root权限,设置当前用户权限*/
172     setuid(getuid());
173     /*扩大套接字接收缓冲区到50K这样做主要为了减小接收缓冲区溢出的的可能性,若无意中ping一个广播地址或多播地址,将会引来大量应答*/
174                    setsockopt(sockfd,SOL_SOCKET,SO_RCVBUF,&size,sizeof(size) );
175      bzero(&dest_addr,sizeof(dest_addr));
176      dest_addr.sin_family=AF_INET;
177      /*判断是主机名还是ip地址*/
178      if( inaddr=inet_addr(argv[1])==INADDR_NONE)
179      {       
180         if((host=gethostbyname(argv[1]) )==NULL) /*是主机名*/
181         {       
182             perror("gethostbyname error");
183             exit(1);
184         }
185         memcpy( (char *)&dest_addr.sin_addr,host->h_addr,host->h_length);
186      }
187      else    /*是ip地址*/
188          memcpy( (char *)&dest_addr,(char *)&inaddr,host->h_length);
189     /*获取main的进程id,用于设置ICMP的标志符*/
190     pid=getpid();
191     printf("PING %s(%s): %d bytes data in ICMP packets.\n",argv[1],inet_ntoa(dest_addr.sin_addr),datalen);
192     send_packet();  /*发送所有ICMP报文*/
193     recv_packet();  /*接收所有ICMP报文*/
194     statistics(SIGALRM); /*进行统计*/
195     return 0;
196 }
197 /*两个timeval结构相减*/
198 void tv_sub(struct timeval *out,struct timeval *in)
199 {       
200     if( (out->tv_usec-=in->tv_usec)<0)
201     {       
202         --out->tv_sec;
203         out->tv_usec+=1000000;
204     }
205     out->tv_sec-=in->tv_sec;
206 }
207 /*------------- The End -----------*/                    

仍然需要注意权限的问题,按照如下方式编译:

sudo gcc myping.c -o myping

sudo chmod u+s myping

./myping www.163.com

运行显示结果:

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

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

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

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

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

3 packets transmitted, 3 received , %0 lost

posted on 2013-08-08 17:04  千兵卫博士  阅读(1757)  评论(0编辑  收藏  举报

导航