ping源码

[html]  view plain copy
  1.     
  2.     http://www.rfc-editor.org/rfc/rfc791.txt  
  3.     
  4.     0                   1                   2                   3     
  5.     0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1   
  6.    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+  
  7.    |Version|  IHL  |Type of Service|          Total Length         |  
  8.    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+  
  9.    |         Identification        |Flags|      Fragment Offset    |  
  10.    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+  
  11.    |  Time to Live |    Protocol   |         Header Checksum       |  
  12.    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+  
  13.    |                       Source Address                          |  
  14.    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+  
  15.    |                    Destination Address                        |  
  16.    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+  
  17.    |                    Options                    |    Padding    |  
  18.    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+  
  19.   
  20. struct ip  
  21. {  
  22. #if __BYTE_ORDER == __LITTLE_ENDIAN  
  23.     unsigned int ip_hl:4;       /* header length */  
  24.     unsigned int ip_v:4;        /* version */  
  25. #endif  
  26. #if __BYTE_ORDER == __BIG_ENDIAN  
  27.     unsigned int ip_v:4;        /* version */  
  28.     unsigned int ip_hl:4;       /* header length */  
  29. #endif  
  30.     u_int8_t ip_tos;            /* type of service */  
  31.     u_short ip_len;         /* total length */  
  32.     u_short ip_id;          /* identification */  
  33.     u_short ip_off;         /* fragment offset field */  
  34. #define IP_RF 0x8000            /* reserved fragment flag */  
  35. #define IP_DF 0x4000            /* dont fragment flag */  
  36. #define IP_MF 0x2000            /* more fragments flag */  
  37. #define IP_OFFMASK 0x1fff       /* mask for fragmenting bits */  
  38.     u_int8_t ip_ttl;            /* time to live */  
  39.     u_int8_t ip_p;          /* protocol */  
  40.     u_short ip_sum;         /* checksum */  
  41.     struct in_addr ip_src, ip_dst;  /* source and dest address */  
  42. };  

TCP/IP教程:http://www.rfc-editor.org/rfc/rfc1180.txt

TCP/IP协议校验和算法:http://www.rfc-editor.org/rfc/rfc1071.txt

[cpp]  view plain copy
  1. #include <string.h>  
  2. #include <stdlib.h>  
  3. #include <stdio.h>  
  4. #include <signal.h>  
  5. #include <arpa/inet.h>  
  6. #include <sys/types.h>  
  7. #include <sys/socket.h>  
  8. #include <unistd.h>  
  9. #include <netinet/in.h>  
  10. #include <netinet/ip.h>  
  11. #inlcude <netinet/ip_icmp.h>  
  12. #include <netdb.h>  
  13. #include <setjmp.h>  
  14. #inlcude <errno.h>  
  15.   
  16. #define PACKET_SIZE     4096  
  17. #define MAX_WAIT_TIME   5  
  18. #define MAX_NO_PACKETS  3  
  19.   
  20. char sendpacket[PACKET_SIZE];  
  21. char recvpacket[PACKET_SIZE];  
  22.   
  23. int datalen = 56;  
  24. int nsend = 0, nreceived = 0;  
  25.   
  26. int sockfd;  
  27. struct sockaddr_in  dest_addr, from;  
  28. struct timeval tvrecv;  
  29. pid_t pid;  
  30.   
  31. void statistics(int signo);  
  32. unsigned short cal_checksum(unsigned short *addr, int len);  
  33. int pack(int pack_no);  
  34. void send_packet(void);  
  35. void recv_packet(void);  
  36. int unpack(char *buf, int len);  
  37. void tv_sub(struct timeval *out,struct timeval *in);  
  38.   
  39. void statistics(int signo)  
  40. {  
  41.     printf("\n-------------PING statistics---------------\n");  
  42.     printf("%d packet transmitted , %d received, %%%d lost\n",nsend, nreceived, \  
  43.              (nsend-nreceived)/nsend*100);  
  44.     close(sockfd);  
  45.     exit(1);  
  46. }  
  47.   
  48. /*-------校验和算法--------*/  
  49. unsigned short cal_checksum(unsigned short *addr, int len)  
  50. {  
  51.     int nleft = len;  
  52.     int sum = 0;  
  53.     unsigned short *w = addr;  
  54.     unsigned short answer = 0;  
  55.       
  56.     /*--将ICMP报头二进制数据以2字节为单位累加--*/  
  57.     while(nleft > 1)  
  58.     {  
  59.         sum += *w++;  
  60.         nleft -= 2;  
  61.     }  
  62.       
  63.     /*--若ICMP报头为奇数个字节,把最后一个字节最为一个2字节数据的高字节,低字节为0,继续累加--*/  
  64.     if( nleft == 1 )  
  65.     {  
  66.         *(unsigned char *)(&answer) = *(unsigned char *)w;  
  67.         sum += answer;  
  68.     }  
  69.       
  70.     sum = (sum>>16) + (sum & 0xffff);  
  71.     sum += (sum>>16);  
  72.     answer = ~sum;  
  73.       
  74.     return answer;  
  75. }  
  76.   
  77. /*---设置ICMP报头---*/  
  78. int pack(int pack_no)  
  79. {  
  80.     int i, packsize;  
  81.     struct icmp *icmp;  
  82.     struct timeval *tval;  
  83.       
  84.     icmp = (struct icmp*)sendpacket;  
  85.     icmp->icmp_type = ICMP_ECHO;  
  86.     icmp->icmp_code = 0;  
  87.     icmp->icmp_cksum = 0;  
  88.     icmp->icmp_seq = pack_no;  
  89.     icmp->icmp_id = pid;  
  90.     packsize = 8 + datalen;  
  91.       
  92.     tval = (struct timeval *)icmp->icmp_data;  
  93.     gettimeofday(tval,NULL);/*记录发送时间*/  
  94.     icmp->icmp_cksum = cal_chksum((unsigned short *)icmp, packsize);/*校验算法*/  
  95.       
  96.     return packsize;  
  97. }  
  98.   
  99. /*---发送三个报文---*/  
  100. void send_packet()  
  101. {  
  102.     int packetsize;  
  103.     while( nsend < MAX_NO_PACKETS )  
  104.     {  
  105.         nsend++;  
  106.         packetsize = pack(nsend);/*设置ICMP报头*/  
  107.         if( sendto(sockfd, sendpacket, packetsize, 0,   
  108.                     (struct sockaddr *)&dest_addr, sizeof(dest_addr)) < 0 )  
  109.         {  
  110.             perror("sendto error");  
  111.             continue;  
  112.         }  
  113.           
  114.         sleep(1); /*每隔一秒发送一个ICMP报文*/  
  115.     }  
  116. }  
  117.           
  118. void recv_packet()  
  119. {  
  120.     int n, fromlen;  
  121.     extern int errno;  
  122.       
  123.     signal(SIGALRM,statistics);  
  124.     fromlen = sizeof(from);  
  125.     while(nreceived < nsend)  
  126.     {  
  127.         alarm(MAX_WAIT_TIME);  
  128.           
  129.         if((n = recvfrom(sockfd, recvpacket, sizeof(recvpacket), 0,  
  130.                         (struct sockaddr *)&from, &fromlen)) < 0)  
  131.         {  
  132.             if(errno == EINTR)  
  133.                 continue;  
  134.             perror(recvfrom error");  
  135.             continue;  
  136.         }  
  137.         gettimeofday(&tvrecv,NULL); /*记录接收时间*/  
  138.         if(unpack(recvpacket,n) == -1)  
  139.             continue;  
  140.         nreceived++;  
  141.     }     
  142. }  
  143.   
  144. int unpack(char *buf, int len)  
  145. {  
  146.     int i, iphdrlen;  
  147.     struct ip *ip;  
  148.     struct icmp *icmp;  
  149.     struct timeval *tvsend;  
  150.     double rtt;  
  151.       
  152.     ip = (struct ip *)buf;  
  153.     iphdrlen = ip->ip_hl<<2; /*求ip报头长度,即ip报头的长度标志乘4*/  
  154.     icmp = (struct icmp *)(buf + iphdrlen); /*越过ip报头,指向ICMP报头*/  
  155.     len -= iphdrlen;  /*ICMP报头及ICMP数据报的总长度*/  
  156.     if( len < 8 )  
  157.     {  
  158.         printf("ICMP packet\'s length is less than 8\n");  
  159.         return -1;  
  160.     }  
  161.       
  162.     /*确保所收到的是我所发的ICMP的回应*/  
  163.     if(( icmp->icmp_type == ICMP_ECHOREPLY ) && (icmp->icmp_id == pid))  
  164.     {  
  165.         tvsend = (struct timeval *)icmp->icmp_data;  
  166.         tv_sub(&tvrecv, tvsend); /*接收和发送的时间差*/  
  167.         rtt = tvrecv.tv_sec * 1000 + tvrecv.tv_usec / 1000; /*以毫秒为单位计算rtt*/  
  168.           
  169.         /*显示相关信息*/  
  170.         printf("%d byte from %s:icmp_seq = %u ttl = %d rtt = %.3f ms\n",  
  171.                 len,  
  172.                 inet_ntoa(from.sin_addr),  
  173.                 icmp->icmp_seq,  
  174.                 ip->ttl,  
  175.                 rtt);  
  176.     }  
  177.     else   
  178.         return -1;  
  179. }  
  180.   
  181. int main(int argc, char *argv[])  
  182. {  
  183.     struct hostent *host;  
  184.     struct protoent *protocol;  
  185.     unsigned long inaddr = 0L;  
  186.     int waittime = MAX_WAIT_TIME;  
  187.     int size = 50 * 1024;  
  188.       
  189.     if( argc < 2 )  
  190.     {  
  191.         printf("usage:%s hostname / IP address\n", argv[0]);  
  192.         exit(1);  
  193.     }  
  194.       
  195.     if((protocol = getprotobyname("icmp")) == NULL)  
  196.     {  
  197.         perror("getprotobyname");  
  198.         exit(1);  
  199.     }  
  200.       
  201.     /*生成使用ICMP的原始套接字,这种套接字只有root才能生成*/  
  202.     if(( sockfd = socket(AF_INET, SOCK_RAW, protocol->p_proto)) < 0)  
  203.     {  
  204.         perror("socket error");  
  205.         exit(1);  
  206.     }  
  207.       
  208.     /*收回root权限,设置当前用户权限*/  
  209.     setuid(getuid());  
  210.       
  211.     /*扩大套接字接收缓冲区到50K,这样做主要为了减小接收缓冲区溢出的 
  212.       可能性,若无意中ping一个广播地址或多播地址,将会引来大量应答*/  
  213.     setsockopt(sockfd, SOL_SOCKET, SO_RCVBUF, &size, sizeof(size));  
  214.     bzero(&dest_addr, sizeof(dest_addr));  
  215.     dest_addr.sin_family = AF_INET;  
  216.       
  217.     /*判断是主机名还是IP地址*/  
  218.     if( inaddr = inet_addr(argv[1]) == INADDR_NONE)  
  219.     {  
  220.         if((host = gethostbyname(argv[1])) == NULL) /*主机名*/  
  221.         {  
  222.             perror("gethostbyname error");  
  223.             exit(1);  
  224.         }  
  225.           
  226.         memcpy((char *)&dest_addr.sin_addr, host->h_addr, host->h_length);  
  227.     }  
  228.     else  /*是IP地址*/  
  229.         memcpy((char *)&dest_addr, (char *)&inaddr, host->h_length);  
  230.           
  231.     /*获取main的进程id,用于设置ICMP的标志符*/  
  232.     pid = getid();  
  233.     printf("PING %s(%s):%d bytes data in ICMP packets.\n", argv[1], inet_ntoa(dest_addr.sin_addr),datalen);  
  234.     send_packet();  
  235.     recv_packet();  
  236.     statistics(SIGALRM);  
  237.       
  238.     return 0;  
  239. }  
  240.   
  241. void tv_sub(struct timeval *out, struct timeval *in)  
  242. {  
  243.     if((out->tv_usec -= in->tv_usec) < 0 )  
  244.     {  
  245.         --out->tv_sec;  
  246.         out->tv_usec += 1000000;  
  247.     }  
  248.     out->tv_sec -= in->tv_sec;  
  249. }  
  250.   
  251. sudo gcc -o ping ping.c  
  252. sudo chmod u+s ping #目的是把ping程序设置成SUID的属性  
  253.           
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值