Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1359329
  • 博文数量: 704
  • 博客积分: 10140
  • 博客等级: 上将
  • 技术积分: 6230
  • 用 户 组: 普通用户
  • 注册时间: 2010-07-15 20:41
文章分类

全部博文(704)

文章存档

2013年(1)

2012年(16)

2011年(536)

2010年(151)

分类:

2011-11-07 21:48:55

注:本文转自http://www.ibm.com/developerworks/cn/linux/network/ping/index.html,原文发表于2001年,已过去多年,因此进行了很小的一些修改。

简介: 大部分人用ping命令只是作为查看本机到某个ip地址的网络连接是否正常的一种简单方法。在这篇文章中,作者将介绍如何用C语言编写一个模拟ping命令功能的程序。

ping命令是用来查看网络上另一个主机系统的网络连接是否正常的一个工具。ping命令的工作原理是:向网络上的另一个主机系统发送ICMP报文,如果指定系统得到了报文,它将把报文一模一样地传回给发送者,这有点象潜水艇声纳系统中使用的发声装置。
例如,在Linux终端上执行ping localhost命令将会看到以下结果:

  1. PING localhost (127.0.0.1) 56(84) bytes of data.
  2. 64 bytes from localhost (127.0.0.1): icmp_req=1 ttl=64 time=0.040 ms
  3. 64 bytes from localhost (127.0.0.1): icmp_req=2 ttl=64 time=0.032 ms
  4. 64 bytes from localhost (127.0.0.1): icmp_req=3 ttl=64 time=0.031 ms
  5. 64 bytes from localhost (127.0.0.1): icmp_req=4 ttl=64 time=0.016 ms
  6. 64 bytes from localhost (127.0.0.1): icmp_req=5 ttl=64 time=0.015 ms
  7. ^C
  8. --- localhost ping statistics ---
  9. 5 packets transmitted, 5 received, 0% packet loss, time 3996ms
  10. rtt min/avg/max/mdev = 0.015/0.026/0.040/0.011 ms

由上面的执行结果可以看到,ping命令执行后显示出被测试系统主机名和相应IP地址、返回给当前主机的ICMP报文顺序号、ttl生存时间和往返时间rtt(单位是毫秒,即千分之一秒)。要写一个模拟ping命令,这些信息有启示作用。

关于数字56、84、64的含义:

84 - 64 = 20, 84 - 56 = 28, 64 - 56 = 8,而sizeof(struct ip)==20,sizeof(struct icmp)==28。

所以:56(84)的含义是,icmp的总长度位84字节,其中ip部分为20字节,剩下的64字节为icmp的报头和数据,其中28字节位icmp的报头,剩下的54字节位数据部分。64字节说明,目的地址方在接收到我们的icmp查询时,在解包时,将20字节的ip头去掉了,所以对于目的地址方来说,它收到了64字符的内容。

要真正了解ping命令实现原理,就要了解ping命令所使用到的TCP/IP协议。

ICMP(Internet Control Message,网际控制报文协议)是为网关和目标主机而提供的一种差错控制机制,使它们在遇到差错时能把错误报告给报文源发方。ICMP协议是IP层的一个协议,但是由于差错报告在发送给报文源发方时可能也要经过若干子网,因此牵涉到路由选择等问题,所以ICMP报文需通过IP协议来发送。ICMP数据报的数据发送前需要两级封装:首先添加ICMP报头形成ICMP报文,再添加IP报头形成IP数据报。如下图所示

IP报头
ICMP报头
ICMP数据报

由于IP层协议是一种点对点的协议,而非端对端的协议,它提供无连接的数据报服务,没有端口的概念,因此很少使用bind()和connect()函数,若有使用也只是用于设置IP地址。发送数据使用sendto()函数,接收数据使用recvfrom()函数。IP报头格式如下图:
 
在Linux中,IP报头格式数据结构()定义如下:(Linux ubuntu 2.6.38-8-generic下同)

  1. struct timestamp
  2. {
  3.     u_int8_t len;
  4.     u_int8_t ptr;
  5. #if __BYTE_ORDER == __LITTLE_ENDIAN
  6.     unsigned int flags:4;
  7.     unsigned int overflow:4;
  8. #elif __BYTE_ORDER == __BIG_ENDIAN
  9.     unsigned int overflow:4;
  10.     unsigned int flags:4;
  11. #else
  12. # error "Please fix "
  13. #endif
  14.     u_int32_t data[9];
  15. };

  16. struct iphdr
  17. {
  18. #if __BYTE_ORDER == __LITTLE_ENDIAN
  19.     unsigned int ihl:4;
  20.     unsigned int version:4;
  21. #elif __BYTE_ORDER == __BIG_ENDIAN
  22.     unsigned int version:4;
  23.     unsigned int ihl:4;
  24. #else
  25. # error "Please fix "
  26. #endif
  27.     u_int8_t tos;
  28.     u_int16_t tot_len;
  29.     u_int16_t id;
  30.     u_int16_t frag_off;
  31.     u_int8_t ttl;
  32.     u_int8_t protocol;
  33.     u_int16_t check;
  34.     u_int32_t saddr;
  35.     u_int32_t daddr;
  36.     /*The options start here. */
  37. };

  38. #ifdef __USE_BSD
  39. struct ip
  40. {
  41. #if __BYTE_ORDER == __LITTLE_ENDIAN
  42.     unsigned int ip_hl:4; /* header length */
  43.     unsigned int ip_v:4; /* version */
  44. #endif
  45. #if __BYTE_ORDER == __BIG_ENDIAN
  46.     unsigned int ip_v:4; /* version */
  47.     unsigned int ip_hl:4; /* header length */
  48. #endif
  49.     u_int8_t ip_tos; /* type of service */
  50.     u_short ip_len; /* total length */
  51.     u_short ip_id; /* identification */
  52.     u_short ip_off; /* fragment offset field */
  53. #define IP_RF 0x8000 /* reserved fragment flag */
  54. #define IP_DF 0x4000 /* dont fragment flag */
  55. #define IP_MF 0x2000 /* more fragments flag */
  56. #define IP_OFFMASK 0x1fff /* mask for fragmenting bits */
  57.     u_int8_t ip_ttl; /* time to live */
  58.     u_int8_t ip_p; /* protocol */
  59.     u_short ip_sum; /* checksum */
  60.     struct in_addr ip_src, ip_dst; /* source and dest address */
  61. };

  62. /*
  63.  * Time stamp option structure.
  64.  */
  65. struct ip_timestamp
  66. {
  67.     u_int8_t ipt_code; /* IPOPT_TS */
  68.     u_int8_t ipt_len; /* size of structure (variable) */
  69.     u_int8_t ipt_ptr; /* index of current entry */
  70. #if __BYTE_ORDER == __LITTLE_ENDIAN
  71.     unsigned int ipt_flg:4; /* flags, see below */
  72.     unsigned int ipt_oflw:4; /* overflow counter */
  73. #endif
  74. #if __BYTE_ORDER == __BIG_ENDIAN
  75.     unsigned int ipt_oflw:4; /* overflow counter */
  76.     unsigned int ipt_flg:4; /* flags, see below */
  77. #endif
  78.     u_int32_t data[9];
  79. };
  80. #endif /* __USE_BSD */

其中ping程序只使用以下数据:

  • IP报头长度IHL(Internet Header Length)以4字节为一个单位来记录IP报头的长度,是上述IP数据结构的ihl变量。
  • 生存时间TTL(Time To Live)以秒为单位,指出IP数据报能在网络上停留的最长时间,其值由发送方设定,并在经过路由的每一个节点时减一,当该值为0时,数据报将被丢弃,是上述IP数据结构的ttl变量。

ICMP报文分为两种,一是错误报告报文,二是查询报文。每个ICMP报头均包含类型、编码和校验和这三项内容,长度分别为8位,8位和16位,其余选项则随ICMP的功能不同而不同。

Ping命令只使用众多ICMP报文中的两种:"请求回送'(ICMP_ECHO)和"请求回应'(ICMP_ECHOREPLY)。在Linux中定义如下:

  1. #define ICMP_ECHO 8           /* Echo Request */
  2. #define ICMP_ECHOREPLY 0      /* Echo Reply */

这两种ICMP类型报头格式如下:

 

在Linux中ICMP数据结构()定义如下:

  1. struct icmphdr
  2. {
  3.   u_int8_t type; /* message type */
  4.   u_int8_t code; /* type sub-code */
  5.   u_int16_t checksum;
  6.   union
  7.   {
  8.     struct
  9.     {
  10.       u_int16_t id;
  11.       u_int16_t sequence;
  12.     } echo; /* echo datagram */
  13.     u_int32_t gateway; /* gateway address */
  14.     struct
  15.     {
  16.       u_int16_t __unused;
  17.       u_int16_t mtu;
  18.     } frag; /* path mtu discovery */
  19.   } un;
  20. };
  21. #ifdef __USE_BSD

  22. #include <netinet/in.h>
  23. #include <netinet/ip.h>

  24. /*
  25.  * Internal of an ICMP Router Advertisement
  26.  */
  27. struct icmp_ra_addr
  28. {
  29.   u_int32_t ira_addr;
  30.   u_int32_t ira_preference;
  31. };

  32. struct icmp
  33. {
  34.   u_int8_t icmp_type; /* type of message, see below */
  35.   u_int8_t icmp_code; /* type sub code */
  36.   u_int16_t icmp_cksum; /* ones complement checksum of struct */
  37.   union
  38.   {
  39.     u_char ih_pptr; /* ICMP_PARAMPROB */
  40.     struct in_addr ih_gwaddr; /* gateway address */
  41.     struct ih_idseq /* echo datagram */
  42.     {
  43.       u_int16_t icd_id;
  44.       u_int16_t icd_seq;
  45.     } ih_idseq;
  46.     u_int32_t ih_void;

  47.     /* ICMP_UNREACH_NEEDFRAG -- Path MTU Discovery (RFC1191) */
  48.     struct ih_pmtu
  49.     {
  50.       u_int16_t ipm_void;
  51.       u_int16_t ipm_nextmtu;
  52.     } ih_pmtu;

  53.     struct ih_rtradv
  54.     {
  55.       u_int8_t irt_num_addrs;
  56.       u_int8_t irt_wpa;
  57.       u_int16_t irt_lifetime;
  58.     } ih_rtradv;
  59.   } icmp_hun;
  60. #define icmp_pptr icmp_hun.ih_pptr
  61. #define icmp_gwaddr icmp_hun.ih_gwaddr
  62. #define icmp_id icmp_hun.ih_idseq.icd_id
  63. #define icmp_seq icmp_hun.ih_idseq.icd_seq
  64. #define icmp_void icmp_hun.ih_void
  65. #define icmp_pmvoid icmp_hun.ih_pmtu.ipm_void
  66. #define icmp_nextmtu icmp_hun.ih_pmtu.ipm_nextmtu
  67. #define icmp_num_addrs icmp_hun.ih_rtradv.irt_num_addrs
  68. #define icmp_wpa icmp_hun.ih_rtradv.irt_wpa
  69. #define icmp_lifetime icmp_hun.ih_rtradv.irt_lifetime
  70.   union
  71.   {
  72.     struct
  73.     {
  74.       u_int32_t its_otime;
  75.       u_int32_t its_rtime;
  76.       u_int32_t its_ttime;
  77.     } id_ts;
  78.     struct
  79.     {
  80.       struct ip idi_ip;
  81.       /* options and then 64 bits of data */
  82.     } id_ip;
  83.     struct icmp_ra_addr id_radv;
  84.     u_int32_t id_mask;
  85.     u_int8_t id_data[1];
  86.   } icmp_dun;
  87. #define icmp_otime icmp_dun.id_ts.its_otime
  88. #define icmp_rtime icmp_dun.id_ts.its_rtime
  89. #define icmp_ttime icmp_dun.id_ts.its_ttime
  90. #define icmp_ip icmp_dun.id_ip.idi_ip
  91. #define icmp_radv icmp_dun.id_radv
  92. #define icmp_mask icmp_dun.id_mask
  93. #define icmp_data icmp_dun.id_data
  94. };

struct icmphdr的定义可知,sizeof(struct icmphdr) == 8字节。即ICMP报头为8字节,数据报长度最大为64K字节。

  1. 校验和算法:这一算法称为网际校验和算法,把被校验的数据16位进行累加,然后取反码,若数据字节长度为奇数,则数据尾部补一个字节的0以凑成偶数。此算法适用于IPv4、ICMPv4、IGMPV4、ICMPv6、UDP和TCP校验和,更详细的信息请参考RFC1071,校验和字段为上述ICMP数据结构的icmp_cksum变量。
  2. 标识符:用于唯一标识ICMP报文, 为上述ICMP数据结构中的id。
  3. 顺序号:ping命令的icmp_seq便由这里读出,代表ICMP报文的发送顺序,为上述ICMP数据结构的seq宏所指的变量。

Ping命令中需要显示的信息,包括icmp_seq和ttl都已有实现的办法,但还缺rtt往返时间。为了实现这一功能,可利用ICMP数据报携带一个时间戳。使用以下函数生成时间戳:

  1. #include
  2. int gettimeofday(struct timeval *tp,void *tzp);
  3. struct timeval{
  4.       long tv_sec;     /* seconds */
  5.       long tv_usec;    /* micrseconds */
  6. };

其中tv_sec为秒数,tv_usec微秒数。在发送和接收报文时由gettimeofday分别生成两个timeval结构,两者之差即为往返时间,即ICMP报文发送与接收的时间差,而timeval结构由ICMP数据报携带,tzp指针表示时区,一般都不使用,赋NULL值。

系统自带的ping命令当它接送完所有ICMP报文后,会对所有发送和所有接收的ICMP报文进行统计,从而计算ICMP报文丢失的比率。为达此目的,定义两个全局变量:接收计数器和发送计数器,用于记录ICMP报文接受和发送数目。丢失数目=发送总数-接收总数,丢失比率=丢失数目/发送总数。

现给出模拟Ping程序功能的代码如下:

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <strings.h> /* for bzero */
  5. #include <signal.h>
  6. #include <sys/time.h>
  7. #include <arpa/inet.h>
  8. #include <sys/types.h>
  9. #include <sys/socket.h>
  10. #include <unistd.h>
  11. #include <netinet/in.h>
  12. #include <netinet/ip.h>
  13. #include <netinet/ip_icmp.h>
  14. #include <netdb.h>
  15. #include <setjmp.h>
  16. #include <errno.h>

  17. #define MAX_WAIT_TIME 5
  18. #define PACKET_SIZE 4096    /* 数据包的大小 */
  19. #define MAX_NO_PACKETS 3    /* 发送3个ICMP报文 */

  20. char    sendpacket[PACKET_SIZE];    /* 发送的数据包 */
  21. char    recvpacket[PACKET_SIZE];    /* 接收的数据包 */

  22. pid_t    pid;
  23. int    sockfd;
  24. int    datalen = 56;    /* icmp数据包中数据的长度 */
  25. int    nsend = 0;       /* 发送的次数 */
  26. int    nreceived = 0;   /* 接收的次数 */

  27. struct sockaddr_in    dest_addr;  /* icmp包目的地址 */
  28. struct sockaddr_in    from;       /* icmp包源地址 */
  29. struct timeval    tvrecv;

  30. void statistics(int signo);
  31. unsigned short cal_chksum(unsigned short *addr,int len);
  32. int pack(int pack_no);
  33. void send_packet(void);
  34. void recv_packet(void);
  35. int unpack(char *buf,int len);
  36. void tv_sub(struct timeval *out,struct timeval *in);

  37. void statistics(int signo)
  38. {
  39.         printf("\n--------------------PING statistics-------------------\n");
  40.         /*
  41.          * 总共发送nsend个icmp包,总共接收到返回的nreceived个包,
  42.          * icmp包的丢失率(nsend-nreceived)/nsend
  43.          */
  44.         printf("%d packets transmitted, %d received , %%%d lost\n",
  45.                 nsend, nreceived, (nsend-nreceived)/nsend*100);
  46.         close(sockfd);
  47.         exit(1);
  48. }

  49. /* 计算校验和的算法 */
  50. unsigned short cal_chksum(unsigned short *addr,int len)
  51. {
  52.         int sum=0;
  53.         int nleft = len;
  54.         unsigned short *w = addr;
  55.         unsigned short answer = 0;

  56.         /* 把ICMP报头二进制数据以2字节为单位累加起来 */
  57.         while(nleft > 1){
  58.                 sum += *w++;
  59.                 nleft -= 2;
  60.         }
  61.         /*
  62.          * 若ICMP报头为奇数个字节,会剩下最后一字节。
  63.          * 把最后一个字节视为一个2字节数据的高字节,
  64.          * 这2字节数据的低字节为0,继续累加
  65.          */
  66.         if(nleft == 1){
  67.                 *(unsigned char *)(&answer) = *(unsigned char *)w;
  68.                 sum += answer;    /* 这里将 answer 转换成 int 整数 */
  69.         }
  70.         sum = (sum >> 16) + (sum & 0xffff);        /* 高位低位相加 */
  71.         sum += (sum >> 16);        /* 上一步溢出时,将溢出位也加到sum中 */
  72.         answer = ~sum;             /* 注意类型转换,现在的校验和为16位 */

  73.         return answer;
  74. }

  75. /* 设置ICMP报头,以及将发送的时间设置为ICMP的末尾的数据部分和校验和 */
  76. int pack(int pack_no)
  77. {
  78.         int packsize;
  79.         struct icmp    *icmp;
  80.         struct timeval *tval;

  81.         icmp = (struct icmp*)sendpacket;
  82.         icmp->icmp_type = ICMP_ECHO;    /* icmp的类型 */
  83.         icmp->icmp_code = 0;            /* icmp的编码 */
  84.         icmp->icmp_cksum = 0;           /* icmp的校验和 */
  85.         icmp->icmp_seq = pack_no;       /* icmp的顺序号 */
  86.         icmp->icmp_id = pid;            /* icmp的标志符 */
  87.         packsize = 8 + datalen;   /* icmp8字节的头 加上数据的长度(datalen=56), packsize = 64 */

  88.         tval = (struct timeval *)icmp->icmp_data;    /* 获得icmp结构中最后的数据部分的指针 */
  89.         gettimeofday(tval, NULL); /* 将发送的时间填入icmp结构中最后的数据部分 */

  90.         icmp->icmp_cksum = cal_chksum((unsigned short *)icmp, packsize);/*填充发送方的校验和*/

  91.         return packsize;
  92. }

  93. /* 发送三个ICMP报文 */
  94. void send_packet()
  95. {
  96.         int packetsize;

  97.         /* 每一次发送3个icmp包 */
  98.         while(nsend < MAX_NO_PACKETS){    // #define MAX_NO_PACKETS 3
  99.                 nsend++;
  100.                 packetsize = pack(nsend); /* 设置ICMP报头 */
  101.                 if(sendto(sockfd, sendpacket, packetsize, 0,
  102.                           (struct sockaddr *)&dest_addr, sizeof(dest_addr)) < 0){
  103.                         perror("sendto error");
  104.                         continue;
  105.                 }
  106.                 sleep(1); /* 每隔一秒发送一个ICMP报文 */
  107.         }
  108. }

  109. /* 接收所有ICMP报文 */
  110. void recv_packet()
  111. {
  112.         int n, fromlen;
  113.         extern int errno;

  114.         signal(SIGALRM,statistics);
  115.         fromlen = sizeof(from);        /* icmp包源地址的大小*/

  116.         while(nreceived < nsend){
  117.                 alarm(MAX_WAIT_TIME);
  118.                 if((n = recvfrom(sockfd, recvpacket, sizeof(recvpacket), 0,
  119.                                 (struct sockaddr *)&from, (socklen_t *)&fromlen)) < 0)
  120.                 {
  121.                         if(errno == EINTR)
  122.                             continue;
  123.                         perror("recvfrom error");
  124.                         continue;
  125.                 }
  126.                 gettimeofday(&tvrecv, NULL); /* 记录接收到icmp包时的时间 */
  127.                 if(unpack(recvpacket, n) == -1)
  128.                     continue;
  129.                 nreceived++;
  130.         }
  131. }

  132. /* 对ICMP报头解包 */
  133. int unpack(char *buf, int len)
  134. {
  135.         int iphdrlen;
  136.         struct ip *ip;
  137.         struct icmp *icmp;
  138.         struct timeval *tvsend;
  139.         double rtt;

  140.         ip = (struct ip *)buf;
  141.         iphdrlen = ip->ip_hl << 2;    /* 求ip报头长度,即ip报头的长度标志乘4 */

  142.         icmp = (struct icmp *)(buf + iphdrlen); /* 越过ip报头,指向ICMP报头 */
  143.         len -= iphdrlen;        /* ICMP报头及ICMP数据报的总长度 */
  144.         if(len < 8){                /* 小于ICMP报头长度则不合理 */
  145.                 printf("ICMP packets\'s length is less than 8\n");
  146.                 return -1;
  147.         }
  148.         /* 确保所接收的是我所发的的ICMP的回应 */
  149.         if((icmp->icmp_type == ICMP_ECHOREPLY) && (icmp->icmp_id == pid)){
  150.                 tvsend = (struct timeval *)icmp->icmp_data;
  151.                 tv_sub(&tvrecv, tvsend);   /* 接收和发送的时间差 */
  152.                 /* 以毫秒为单位计算发送和接收的时间差rtt */
  153.                 rtt = tvrecv.tv_sec * 1000 + tvrecv.tv_usec / 1000;
  154.                 /显示相关信息 */
  155.                 printf("%d byte from %s: icmp_seq=%u ttl=%d time=%.3f ms\n",
  156.                         len,        /* ICMP报头及ICMP数据报的总长度 */
  157.                         inet_ntoa(from.sin_addr),    /* ICMP的源地址 */
  158.                         icmp->icmp_seq,        /* icmp包发送的顺序 */
  159.                         ip->ip_ttl,            /* icmp存活的时间 */
  160.                         rtt);        /* 以毫秒为单位计算发送和接收的时间差rtt */
  161.                 return 0;
  162.         }
  163.         else
  164.             return -1;
  165. }

  166. int main(int argc,char *argv[])
  167. {
  168.         struct hostent    *host;
  169.         struct protoent *protocol;
  170.         unsigned long    inaddr = 0l;
  171.         int    size = 50*1024;        //50k

  172.         if(argc < 2){
  173.                 printf("usage:%s hostname/IP address\n",argv[0]);
  174.                 exit(1);
  175.         }
  176.         if((protocol = getprotobyname("icmp")) == NULL){
  177.                 perror("getprotobyname");
  178.                 exit(1);
  179.         }
  180.         /* 生成使用ICMP的原始套接字,这种套接字只有root才能生成 */
  181.         if((sockfd = socket(AF_INET, SOCK_RAW, protocol->p_proto)) < 0){
  182.                 perror("socket error");
  183.                 exit(1);
  184.         }

  185.         setuid(getuid());    /* 回收root权限,设置当前用户权限 */

  186.         /*
  187.          * 扩大套接字接收缓冲区到50K这样做主要为了减小接收缓冲区溢出的
  188.          * 的可能性,若无意中ping一个广播地址或多播地址,将会引来大量应答
  189.          */
  190.         setsockopt(sockfd, SOL_SOCKET, SO_RCVBUF, &size, sizeof(size) );
  191.         bzero(&dest_addr, sizeof(dest_addr));
  192.         dest_addr.sin_family = AF_INET;

  193.         /* 判断argv[1]是主机名还是ip地址 */
  194.         if((inaddr=inet_addr(argv[1])) == INADDR_NONE){
  195.                 if((host = gethostbyname(argv[1])) == NULL){    /* 是主机名 */
  196.                         perror("gethostbyname error");
  197.                         exit(1);
  198.                 }
  199.                 memcpy((char*)&dest_addr.sin_addr, host->h_addr, host->h_length);
  200.         }else /* 是ip地址 */
  201.                 memcpy((char*)&dest_addr.sin_addr, (char*)&inaddr, sizeof(inaddr));

  202.         pid = getpid();        /*获取main的进程id,用于设置ICMP的标志符*/
  203.         printf("PING %s(%s): %d bytes data in ICMP packets.\n",
  204.                 argv[1], inet_ntoa(dest_addr.sin_addr), datalen);

  205.         send_packet();     /* 发送所有ICMP报文 */
  206.         recv_packet();     /* 接收所有ICMP报文 */
  207.         statistics(SIGALRM);     /* 进行统计 */

  208.         return 0;
  209. }

  210. /* 两个timeval结构相减 */
  211. void tv_sub(struct timeval *recv, struct timeval *send){
  212.         if((recv->tv_usec -= send->tv_usec) < 0){
  213.                 --recv->tv_sec;
  214.                 recv->tv_usec += 1000000;
  215.         }
  216.         recv->tv_sec -= send->tv_sec;
  217. }

只有root用户才能利用socket()函数生成原始套接字,要让Linux的一般用户能执行以上程序,需进行如下的特别操作:

用root登陆,编译以上程序:gcc -o myping myping.c,其目的有二:一是编译,二是让myping属于root用户。

再执行chmod u+s myping,目的是把myping程序设成SUID的属性。

  1. PING www.google.com.hk(74.125.71.104): 56 bytes data in ICMP packets.
  2. 64 byte from 74.125.71.104: icmp_seq=1 ttl=52 time=3000.000 ms
  3. 64 byte from 74.125.71.104: icmp_seq=2 ttl=52 time=2000.000 ms
  4. 64 byte from 74.125.71.104: icmp_seq=3 ttl=52 time=1000.000 ms

  5. --------------------PING statistics-------------------
  6. 3 packets transmitted, 3 received , %0 lost

由于myping.c是发送完所有的ICMP报文才去接收,因此第一、第二和第三个ICMP报文的往返时间依此是3秒,2秒,1秒,上述结果中time信息正反映这一事实。

阅读(346) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~