2 * Copyright (c) 1989, 1993
3 * The Regents of the University of California. All rights reserved.
5 * This code is derived from software contributed to Berkeley by
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. Neither the name of the University nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * @(#) Copyright (c) 1989, 1993 The Regents of the University of California. All rights reserved.
33 * @(#)ping.c 8.1 (Berkeley) 6/5/93
34 * $FreeBSD: src/sbin/ping/ping.c,v 1.111 2007/05/21 14:38:45 cognet Exp $
40 * Using the Internet Control Message Protocol (ICMP) "ECHO" facility,
41 * measure round-trip-delays and packet loss across network paths.
45 * U. S. Army Ballistic Research Laboratory
49 * Public Domain. Distribution Unlimited.
51 * More statistics could always be gathered.
52 * This program has to run SUID to ROOT to access the ICMP socket.
55 #include <sys/param.h> /* NB: we rely on this for <sys/types.h> */
56 #include <sys/socket.h>
57 #include <sys/sysctl.h>
61 #include <netinet/in.h>
62 #include <netinet/in_systm.h>
63 #include <netinet/ip.h>
64 #include <netinet/ip_icmp.h>
65 #include <netinet/ip_var.h>
66 #include <arpa/inet.h>
80 #define INADDR_LEN ((int)sizeof(in_addr_t))
81 #define TIMEVAL_LEN ((int)sizeof(struct tv32))
82 #define MASK_LEN (ICMP_MASKLEN - ICMP_MINLEN)
83 #define TS_LEN (ICMP_TSLEN - ICMP_MINLEN)
84 #define DEFDATALEN 56 /* default data length */
85 #define FLOOD_BACKOFF 20000 /* usecs to back off if F_FLOOD mode */
86 /* runs out of buffer space */
87 #define MAXIPLEN (sizeof(struct ip) + MAX_IPOPTLEN)
88 #define MAXICMPLEN (ICMP_ADVLENMIN + MAX_IPOPTLEN)
89 #define MAXWAIT 10000 /* max ms to wait for response */
90 #define MAXALARM (60 * 60) /* max seconds for alarm timeout */
93 #define A(bit) rcvd_tbl[(bit)>>3] /* identify byte in array */
94 #define B(bit) (1 << ((bit) & 0x07)) /* identify bit in byte */
95 #define SET(bit) (A(bit) |= B(bit))
96 #define CLR(bit) (A(bit) &= (~B(bit)))
97 #define TST(bit) (A(bit) & B(bit))
104 /* various options */
106 #define F_FLOOD 0x0001
107 #define F_INTERVAL 0x0002
108 #define F_NUMERIC 0x0004
109 #define F_PINGFILLED 0x0008
110 #define F_QUIET 0x0010
111 #define F_RROUTE 0x0020
112 #define F_SO_DEBUG 0x0040
113 #define F_SO_DONTROUTE 0x0080
114 #define F_VERBOSE 0x0100
115 #define F_QUIET2 0x0200
116 #define F_NOLOOP 0x0400
117 #define F_MTTL 0x0800
119 #define F_AUDIBLE 0x2000
121 #define F_MISSED 0x10000
122 #define F_ONCE 0x20000
123 #define F_HDRINCL 0x40000
124 #define F_MASK 0x80000
125 #define F_TIME 0x100000
126 #define F_SWEEP 0x200000
127 #define F_WAITTIME 0x400000
130 * MAX_DUP_CHK is the number of bits in received table, i.e. the maximum
131 * number of received sequence numbers we can keep track of. Change 128
132 * to 8192 for complete accuracy...
134 #define MAX_DUP_CHK (8 * 128)
135 int mx_dup_ck = MAX_DUP_CHK;
136 char rcvd_tbl[MAX_DUP_CHK / 8];
138 struct sockaddr_in whereto; /* who to ping */
139 int datalen = DEFDATALEN;
141 int s; /* socket file descriptor */
142 u_char outpackhdr[IP_MAXPACKET], *outpack;
143 char BBELL = '\a'; /* characters written for MISSED and AUDIBLE */
144 char BSPACE = '\b'; /* characters written for flood */
148 int ident; /* process id to identify our packets */
149 int uid; /* cached uid for micro-optimization */
150 u_char icmp_type = ICMP_ECHO;
151 u_char icmp_type_rsp = ICMP_ECHOREPLY;
156 long nmissedmax; /* max value of ntransmitted - nreceived - 1 */
157 long npackets; /* max packets to transmit */
158 long nreceived; /* # of packets we got back */
159 long nrepeats; /* number of duplicates */
160 long ntransmitted; /* sequence # for outbound packets = #sent */
161 long snpackets; /* max packets to transmit in one sweep */
162 long snreceived; /* # of packets we got back in this sweep */
163 long sntransmitted; /* # of packets we sent in this sweep */
164 int sweepmax; /* max value of payload in sweep */
165 int sweepmin = 0; /* start value of payload in sweep */
166 int sweepincr = 1; /* payload increment in sweep */
167 int interval = 1000; /* interval between packets, ms */
168 int waittime = MAXWAIT; /* timeout for each packet */
169 long nrcvtimeout = 0; /* # of packets we got back after waittime */
172 int timing; /* flag to do timing */
173 double tmin = 999999999.0; /* minimum round trip time */
174 double tmax = 0.0; /* maximum round trip time */
175 double tsum = 0.0; /* sum of all times, for doing average */
176 double tsumsq = 0.0; /* sum of all times squared, for std. dev. */
178 volatile sig_atomic_t finish_up; /* nonzero if we've been told to finish up */
179 volatile sig_atomic_t siginfo_p;
181 static void fill(char *, char *);
182 static u_short in_cksum(u_short *, int);
183 static void check_status(void);
184 static void finish(void) __dead2;
185 static void pinger(void);
186 static char *pr_addr(struct in_addr);
187 static char *pr_ntime(n_time);
188 static void pr_icmph(struct icmp *);
189 static void pr_iph(struct ip *);
190 static void pr_pack(char *, int, struct sockaddr_in *, struct timeval *);
191 static void pr_retip(struct ip *);
192 static void status(int);
193 static void stopit(int);
194 static void tvsub(struct timeval *, struct timeval *);
195 static void usage(void) __dead2;
198 main(int argc, char **argv)
200 struct sockaddr_in from, sock_in;
201 struct in_addr ifaddr;
202 struct timeval last, intvl;
206 struct sigaction si_sa;
208 u_char *datap, packet[IP_MAXPACKET] __aligned(4);
209 char *ep, *source, *target, *payload;
211 struct sockaddr_in *to;
213 u_long alarmtimeout, ultmp;
214 int almost_done, ch, df, hold, i, icmp_len, mib[4], preload, sockerrno,
216 char ctrl[CMSG_SPACE(sizeof(struct timeval))];
217 char hnamebuf[MAXHOSTNAMELEN], snamebuf[MAXHOSTNAMELEN];
219 char rspace[MAX_IPOPTLEN]; /* record route space */
221 unsigned char loop, mttl;
223 payload = source = NULL;
226 * Do the stuff that we need root priv's for *first*, and
227 * then drop our setuid bit. Save error reporting for
230 s = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
236 alarmtimeout = df = preload = tos = 0;
238 outpack = outpackhdr + sizeof(struct ip);
239 while ((ch = getopt(argc, argv, "Aac:DdfG:g:h:I:i:Ll:M:m:nop:QqRrS:s:T:t:vW:z:")) != -1) {
245 options |= F_AUDIBLE;
248 ultmp = strtoul(optarg, &ep, 0);
249 if (*ep || ep == optarg || ultmp > LONG_MAX || !ultmp)
251 "invalid count of packets to transmit: `%s'",
256 options |= F_HDRINCL;
260 options |= F_SO_DEBUG;
265 err(EX_NOPERM, "-f flag");
268 setbuf(stdout, NULL);
270 case 'G': /* Maximum packet size for ping sweep */
271 ultmp = strtoul(optarg, &ep, 0);
272 if (*ep || ep == optarg)
273 errx(EX_USAGE, "invalid packet size: `%s'",
275 if (uid != 0 && ultmp > DEFDATALEN) {
278 "packet size too large: %lu > %u",
284 case 'g': /* Minimum packet size for ping sweep */
285 ultmp = strtoul(optarg, &ep, 0);
286 if (*ep || ep == optarg)
287 errx(EX_USAGE, "invalid packet size: `%s'",
289 if (uid != 0 && ultmp > DEFDATALEN) {
292 "packet size too large: %lu > %u",
298 case 'h': /* Packet size increment for ping sweep */
299 ultmp = strtoul(optarg, &ep, 0);
300 if (*ep || ep == optarg || ultmp < 1)
301 errx(EX_USAGE, "invalid increment size: `%s'",
303 if (uid != 0 && ultmp > DEFDATALEN) {
306 "packet size too large: %lu > %u",
312 case 'I': /* multicast interface */
313 if (inet_aton(optarg, &ifaddr) == 0)
315 "invalid multicast interface: `%s'",
319 case 'i': /* wait between sending packets */
320 t = strtod(optarg, &ep) * 1000.0;
321 if (*ep || ep == optarg || t > (double)INT_MAX)
322 errx(EX_USAGE, "invalid timing interval: `%s'",
324 options |= F_INTERVAL;
326 if (uid && interval < 1000) {
328 err(EX_NOPERM, "-i interval too short");
336 ultmp = strtoul(optarg, &ep, 0);
337 if (*ep || ep == optarg || ultmp > INT_MAX)
339 "invalid preload value: `%s'", optarg);
342 err(EX_NOPERM, "-l flag");
357 errx(EX_USAGE, "invalid message: `%c'", optarg[0]);
362 ultmp = strtoul(optarg, &ep, 0);
363 if (*ep || ep == optarg || ultmp > MAXTTL)
364 errx(EX_USAGE, "invalid TTL: `%s'", optarg);
369 options |= F_NUMERIC;
374 case 'p': /* fill buffer with user pattern */
375 options |= F_PINGFILLED;
388 options |= F_SO_DONTROUTE;
393 case 's': /* size of packet to send */
394 ultmp = strtoul(optarg, &ep, 0);
395 if (*ep || ep == optarg)
396 errx(EX_USAGE, "invalid packet size: `%s'",
398 if (uid != 0 && ultmp > DEFDATALEN) {
401 "packet size too large: %lu > %u",
406 case 'T': /* multicast TTL */
407 ultmp = strtoul(optarg, &ep, 0);
408 if (*ep || ep == optarg || ultmp > MAXTTL)
409 errx(EX_USAGE, "invalid multicast TTL: `%s'",
415 alarmtimeout = strtoul(optarg, &ep, 0);
416 if ((alarmtimeout < 1) || (alarmtimeout == ULONG_MAX))
417 errx(EX_USAGE, "invalid timeout: `%s'",
419 if (alarmtimeout > MAXALARM)
420 errx(EX_USAGE, "invalid timeout: `%s' > %d",
422 alarm((int)alarmtimeout);
425 options |= F_VERBOSE;
427 case 'W': /* wait ms for answer */
428 t = strtod(optarg, &ep);
429 if (*ep || ep == optarg || t > (double)INT_MAX)
430 errx(EX_USAGE, "invalid timing interval: `%s'",
432 options |= F_WAITTIME;
436 options |= F_HDRINCL;
437 ultmp = strtoul(optarg, &ep, 0);
438 if (*ep || ep == optarg || ultmp > MAXTOS)
439 errx(EX_USAGE, "invalid TOS: `%s'", optarg);
447 if (argc - optind != 1)
449 target = argv[optind];
451 switch (options & (F_MASK|F_TIME)) {
454 icmp_type = ICMP_MASKREQ;
455 icmp_type_rsp = ICMP_MASKREPLY;
457 if (!(options & F_QUIET))
458 printf("ICMP_MASKREQ\n");
461 icmp_type = ICMP_TSTAMP;
462 icmp_type_rsp = ICMP_TSTAMPREPLY;
464 if (!(options & F_QUIET))
465 printf("ICMP_TSTAMP\n");
468 errx(EX_USAGE, "ICMP_TSTAMP and ICMP_MASKREQ are exclusive.");
471 icmp_len = sizeof(struct ip) + ICMP_MINLEN + phdr_len;
472 if (options & F_RROUTE)
473 icmp_len += MAX_IPOPTLEN;
474 maxpayload = IP_MAXPACKET - icmp_len;
475 if (datalen > maxpayload)
476 errx(EX_USAGE, "packet size too large: %d > %d", datalen,
478 send_len = icmp_len + datalen;
479 datap = &outpack[ICMP_MINLEN + phdr_len + TIMEVAL_LEN];
480 if (options & F_PINGFILLED) {
481 fill((char *)datap, payload);
484 bzero((char *)&sock_in, sizeof(sock_in));
485 sock_in.sin_family = AF_INET;
486 if (inet_aton(source, &sock_in.sin_addr) != 0) {
489 hp = gethostbyname2(source, AF_INET);
491 errx(EX_NOHOST, "cannot resolve %s: %s",
492 source, hstrerror(h_errno));
494 sock_in.sin_len = sizeof sock_in;
495 if ((unsigned)hp->h_length > sizeof(sock_in.sin_addr) ||
497 errx(1, "gethostbyname2: illegal address");
498 memcpy(&sock_in.sin_addr, hp->h_addr_list[0],
499 sizeof(sock_in.sin_addr));
500 strncpy(snamebuf, hp->h_name,
501 sizeof(snamebuf) - 1);
502 snamebuf[sizeof(snamebuf) - 1] = '\0';
503 shostname = snamebuf;
505 if (bind(s, (struct sockaddr *)&sock_in, sizeof sock_in) == -1)
509 bzero(&whereto, sizeof(whereto));
511 to->sin_family = AF_INET;
512 to->sin_len = sizeof *to;
513 if (inet_aton(target, &to->sin_addr) != 0) {
516 hp = gethostbyname2(target, AF_INET);
518 errx(EX_NOHOST, "cannot resolve %s: %s",
519 target, hstrerror(h_errno));
521 if ((unsigned)hp->h_length > sizeof(to->sin_addr))
522 errx(1, "gethostbyname2 returned an illegal address");
523 memcpy(&to->sin_addr, hp->h_addr_list[0], sizeof to->sin_addr);
524 strncpy(hnamebuf, hp->h_name, sizeof(hnamebuf) - 1);
525 hnamebuf[sizeof(hnamebuf) - 1] = '\0';
529 if (options & F_FLOOD && options & F_INTERVAL)
530 errx(EX_USAGE, "-f and -i: incompatible options");
532 if (options & F_FLOOD && IN_MULTICAST(ntohl(to->sin_addr.s_addr)))
534 "-f flag cannot be used with multicast destination");
535 if (options & (F_MIF | F_NOLOOP | F_MTTL)
536 && !IN_MULTICAST(ntohl(to->sin_addr.s_addr)))
538 "-I, -L, -T flags cannot be used with unicast destination");
540 if (datalen >= TIMEVAL_LEN) /* can we time transfer */
543 if (!(options & F_PINGFILLED))
544 for (i = TIMEVAL_LEN; i < datalen; ++i)
547 ident = getpid() & 0xFFFF;
551 err(EX_OSERR, "socket");
554 if (options & F_SO_DEBUG)
555 setsockopt(s, SOL_SOCKET, SO_DEBUG, (char *)&hold,
557 if (options & F_SO_DONTROUTE)
558 setsockopt(s, SOL_SOCKET, SO_DONTROUTE, (char *)&hold,
560 if (options & F_HDRINCL) {
561 ip = (struct ip*)outpackhdr;
562 if (!(options & (F_TTL | F_MTTL))) {
566 mib[3] = IPCTL_DEFTTL;
568 if (sysctl(mib, 4, &ttl, &sz, NULL, 0) == -1)
569 err(1, "sysctl(net.inet.ip.ttl)");
571 setsockopt(s, IPPROTO_IP, IP_HDRINCL, &hold, sizeof(hold));
572 ip->ip_v = IPVERSION;
573 ip->ip_hl = sizeof(struct ip) >> 2;
576 ip->ip_off = df ? IP_DF : 0;
578 ip->ip_p = IPPROTO_ICMP;
579 ip->ip_src.s_addr = source ? sock_in.sin_addr.s_addr : INADDR_ANY;
580 ip->ip_dst = to->sin_addr;
582 /* record route option */
583 if (options & F_RROUTE) {
585 bzero(rspace, sizeof(rspace));
586 rspace[IPOPT_OPTVAL] = IPOPT_RR;
587 rspace[IPOPT_OLEN] = sizeof(rspace) - 1;
588 rspace[IPOPT_OFFSET] = IPOPT_MINOFF;
589 rspace[sizeof(rspace) - 1] = IPOPT_EOL;
590 if (setsockopt(s, IPPROTO_IP, IP_OPTIONS, rspace,
592 err(EX_OSERR, "setsockopt IP_OPTIONS");
595 "record route not available in this implementation");
596 #endif /* IP_OPTIONS */
599 if (options & F_TTL) {
600 if (setsockopt(s, IPPROTO_IP, IP_TTL, &ttl,
602 err(EX_OSERR, "setsockopt IP_TTL");
605 if (options & F_NOLOOP) {
606 if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_LOOP, &loop,
608 err(EX_OSERR, "setsockopt IP_MULTICAST_LOOP");
611 if (options & F_MTTL) {
612 if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL, &mttl,
614 err(EX_OSERR, "setsockopt IP_MULTICAST_TTL");
617 if (options & F_MIF) {
618 if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_IF, &ifaddr,
619 sizeof(ifaddr)) < 0) {
620 err(EX_OSERR, "setsockopt IP_MULTICAST_IF");
625 if (setsockopt(s, SOL_SOCKET, SO_TIMESTAMP, &on, sizeof(on)) < 0)
626 err(EX_OSERR, "setsockopt SO_TIMESTAMP");
630 if (sweepmin >= sweepmax)
631 errx(EX_USAGE, "Maximum packet size must be greater than the minimum packet size");
633 if (datalen != DEFDATALEN)
634 errx(EX_USAGE, "Packet size and ping sweep are mutually exclusive");
637 snpackets = npackets;
642 send_len = icmp_len + sweepmin;
644 if (options & F_SWEEP && !sweepmax)
645 errx(EX_USAGE, "Maximum sweep size must be specified");
648 * When pinging the broadcast address, you can get a lot of answers.
649 * Doing something so evil is useful if you are trying to stress the
650 * ethernet, or just want to fill the arp cache to get some stuff for
651 * /etc/ethers. But beware: RFC 1122 allows hosts to ignore broadcast
652 * or multicast pings if they wish.
656 * XXX receive buffer needs undetermined space for mbuf overhead
659 hold = IP_MAXPACKET + 128;
660 setsockopt(s, SOL_SOCKET, SO_RCVBUF, (char *)&hold,
663 setsockopt(s, SOL_SOCKET, SO_SNDBUF, (char *)&hold,
666 if (to->sin_family == AF_INET) {
667 printf("PING %s (%s)", hostname,
668 inet_ntoa(to->sin_addr));
670 printf(" from %s", shostname);
672 printf(": (%d ... %d) data bytes\n",
675 printf(": %d data bytes\n", datalen);
679 printf("PING %s: (%d ... %d) data bytes\n",
680 hostname, sweepmin, sweepmax);
682 printf("PING %s: %d data bytes\n", hostname, datalen);
686 * Use sigaction() instead of signal() to get unambiguous semantics,
687 * in particular with SA_RESTART not set.
690 sigemptyset(&si_sa.sa_mask);
693 si_sa.sa_handler = stopit;
694 if (sigaction(SIGINT, &si_sa, 0) == -1) {
695 err(EX_OSERR, "sigaction SIGINT");
698 si_sa.sa_handler = status;
699 if (sigaction(SIGINFO, &si_sa, 0) == -1) {
700 err(EX_OSERR, "sigaction");
703 if (alarmtimeout > 0) {
704 si_sa.sa_handler = stopit;
705 if (sigaction(SIGALRM, &si_sa, 0) == -1)
706 err(EX_OSERR, "sigaction SIGALRM");
709 bzero(&msg, sizeof(msg));
710 msg.msg_name = &from;
714 msg.msg_control = ctrl;
716 iov.iov_base = (char *)packet;
717 iov.iov_len = IP_MAXPACKET;
720 pinger(); /* send the first ping */
722 if (npackets != 0 && preload > npackets)
724 while (preload--) /* fire off them quickies */
727 gettimeofday(&last, NULL);
729 if (options & F_FLOOD) {
731 intvl.tv_usec = 10000;
733 intvl.tv_sec = interval / 1000;
734 intvl.tv_usec = interval % 1000 * 1000;
739 struct timeval now, timeout;
744 if ((unsigned)s >= FD_SETSIZE)
745 errx(EX_OSERR, "descriptor too large");
748 gettimeofday(&now, NULL);
749 timeout.tv_sec = last.tv_sec + intvl.tv_sec - now.tv_sec;
750 timeout.tv_usec = last.tv_usec + intvl.tv_usec - now.tv_usec;
751 while (timeout.tv_usec < 0) {
752 timeout.tv_usec += 1000000;
755 while (timeout.tv_usec >= 1000000) {
756 timeout.tv_usec -= 1000000;
759 if (timeout.tv_sec < 0)
760 timeout.tv_sec = timeout.tv_usec = 0;
761 n = select(s + 1, &rfds, NULL, NULL, &timeout);
763 continue; /* Must be EINTR. */
765 struct timeval *tv = NULL;
767 struct cmsghdr *cmsg = (struct cmsghdr *)&ctrl;
769 msg.msg_controllen = sizeof(ctrl);
771 msg.msg_namelen = sizeof(from);
772 if ((cc = recvmsg(s, &msg, 0)) < 0) {
779 if (cmsg->cmsg_level == SOL_SOCKET &&
780 cmsg->cmsg_type == SCM_TIMESTAMP &&
781 cmsg->cmsg_len == CMSG_LEN(sizeof *tv)) {
782 /* Copy to avoid alignment problems: */
783 memcpy(&now, CMSG_DATA(cmsg), sizeof(now));
788 gettimeofday(&now, NULL);
791 pr_pack((char *)packet, cc, &from, tv);
792 if ((options & F_ONCE && nreceived) ||
793 (npackets && nreceived >= npackets))
796 if (n == 0 || options & F_FLOOD) {
797 if (sweepmax && sntransmitted == snpackets) {
798 for (i = 0; i < sweepincr ; ++i)
800 datalen += sweepincr;
801 if (datalen > sweepmax)
803 send_len = icmp_len + datalen;
806 if (!npackets || ntransmitted < npackets)
814 intvl.tv_sec = 2 * tmax / 1000;
818 intvl.tv_sec = waittime / 1000;
819 intvl.tv_usec = waittime % 1000 * 1000;
822 gettimeofday(&last, NULL);
823 if (ntransmitted - nreceived - 1 > nmissedmax) {
824 nmissedmax = ntransmitted - nreceived - 1;
825 if (options & F_MISSED)
826 write(STDOUT_FILENO, &BBELL, 1);
832 exit(0); /* Make the compiler happy */
837 * Set the global bit that causes the main loop to quit.
838 * Do NOT call finish() from here, since finish() does far too much
839 * to be called from a signal handler.
842 stopit(int sig __unused)
846 * When doing reverse DNS lookups, the finish_up flag might not
847 * be noticed for a while. Just exit if we get a second SIGINT.
849 if (!(options & F_NUMERIC) && finish_up)
850 _exit(nreceived ? 0 : 2);
856 * Compose and transmit an ICMP ECHO REQUEST packet. The IP packet
857 * will be added on by the kernel. The ID field is our UNIX process ID,
858 * and the sequence number is an ascending integer. The first TIMEVAL_LEN
859 * bytes of the data portion are used to hold a UNIX "timeval" struct in
860 * host byte-order, to compute the round-trip time.
873 icp = (struct icmp *)outpack;
874 icp->icmp_type = icmp_type;
877 icp->icmp_seq = htons(ntransmitted);
878 icp->icmp_id = ident; /* ID */
880 CLR(ntransmitted % mx_dup_ck);
882 if ((options & F_TIME) || timing) {
883 gettimeofday(&now, NULL);
885 tv32.tv32_sec = htonl(now.tv_sec);
886 tv32.tv32_usec = htonl(now.tv_usec);
887 if (options & F_TIME)
888 icp->icmp_otime = htonl((now.tv_sec % (24*60*60))
889 * 1000 + now.tv_usec / 1000);
892 (void *)&outpack[ICMP_MINLEN + phdr_len],
896 cc = ICMP_MINLEN + phdr_len + datalen;
898 /* compute ICMP checksum here */
899 icp->icmp_cksum = in_cksum((u_short *)icp, cc);
901 if (options & F_HDRINCL) {
902 cc += sizeof(struct ip);
903 ip = (struct ip *)outpackhdr;
905 ip->ip_sum = in_cksum((u_short *)outpackhdr, cc);
908 i = sendto(s, (char *)packet, cc, 0, (struct sockaddr *)&whereto,
911 if (i < 0 || i != cc) {
913 if (options & F_FLOOD && errno == ENOBUFS) {
914 usleep(FLOOD_BACKOFF);
919 warn("%s: partial write: %d of %d bytes",
925 if (!(options & F_QUIET) && options & F_FLOOD)
926 write(STDOUT_FILENO, &DOT, 1);
931 * Print out the packet, if it came from us. This logic is necessary
932 * because ALL readers of the ICMP socket get a copy of ALL ICMP packets
933 * which arrive ('tis only fair). This permits multiple copies of this
934 * program to be run without having intermingled output (or statistics!).
937 pr_pack(char *buf, int cc, struct sockaddr_in *from, struct timeval *tv)
945 int dupflag, hlen, i, j, recv_len, seq;
946 static int old_rrlen;
947 static char old_rr[MAX_IPOPTLEN];
949 /* Check the IP header */
950 ip = (struct ip *)buf;
951 hlen = ip->ip_hl << 2;
953 if (cc < hlen + ICMP_MINLEN) {
954 if (options & F_VERBOSE)
955 warn("packet too short (%d bytes) from %s", cc,
956 inet_ntoa(from->sin_addr));
960 /* Now the ICMP part */
962 icp = (struct icmp *)(buf + hlen);
963 if (icp->icmp_type == icmp_type_rsp) {
964 if (icp->icmp_id != ident)
965 return; /* 'Twas not our ECHO */
976 tp = (const char *)tp + phdr_len;
978 if (cc - ICMP_MINLEN - phdr_len >= (int)sizeof(tv1)) {
979 /* Copy to avoid alignment problems: */
980 memcpy(&tv32, tp, sizeof(tv32));
981 tv1.tv_sec = ntohl(tv32.tv32_sec);
982 tv1.tv_usec = ntohl(tv32.tv32_usec);
984 triptime = ((double)tv->tv_sec) * 1000.0 +
985 ((double)tv->tv_usec) / 1000.0;
987 tsumsq += triptime * triptime;
996 seq = ntohs(icp->icmp_seq);
998 if (TST(seq % mx_dup_ck)) {
1003 SET(seq % mx_dup_ck);
1007 if (options & F_QUIET)
1010 if (options & F_WAITTIME && triptime > waittime) {
1015 if (options & F_FLOOD)
1016 write(STDOUT_FILENO, &BSPACE, 1);
1018 printf("%d bytes from %s: icmp_seq=%u", cc,
1019 inet_ntoa(*(struct in_addr *)&from->sin_addr.s_addr),
1021 printf(" ttl=%d", ip->ip_ttl);
1023 printf(" time=%.3f ms", triptime);
1026 if (options & F_AUDIBLE)
1027 write(STDOUT_FILENO, &BBELL, 1);
1028 if (options & F_MASK) {
1029 /* Just prentend this cast isn't ugly */
1031 pr_addr(*(struct in_addr *)&(icp->icmp_mask)));
1033 if (options & F_TIME) {
1034 printf(" tso=%s", pr_ntime(icp->icmp_otime));
1035 printf(" tsr=%s", pr_ntime(icp->icmp_rtime));
1036 printf(" tst=%s", pr_ntime(icp->icmp_ttime));
1038 if (recv_len != send_len) {
1040 "\nwrong total length %d instead of %d",
1041 recv_len, send_len);
1043 /* check the data */
1044 cp = (u_char*)&icp->icmp_data[phdr_len];
1045 dp = &outpack[ICMP_MINLEN + phdr_len];
1046 cc -= ICMP_MINLEN + phdr_len;
1048 if (timing) { /* don't check variable timestamp */
1054 for (; i < datalen && cc > 0; ++i, ++cp, ++dp, --cc) {
1056 printf("\nwrong data byte #%d should be 0x%x but was 0x%x",
1059 cp = (u_char*)&icp->icmp_data[0];
1060 for (i = 0; i < datalen; ++i, ++cp) {
1063 printf("%2x ", *cp);
1066 cp = &outpack[ICMP_MINLEN];
1067 for (i = 0; i < datalen; ++i, ++cp) {
1070 printf("%2x ", *cp);
1078 * We've got something other than an ECHOREPLY.
1079 * See if it's a reply to something that we sent.
1080 * We can compare IP destination, protocol,
1081 * and ICMP type and ID.
1083 * Only print all the error messages if we are running
1084 * as root to avoid leaking information not normally
1085 * available to those not running as root.
1088 struct ip *oip = &icp->icmp_ip;
1090 struct ip *oip = (struct ip *)icp->icmp_data;
1092 struct icmp *oicmp = (struct icmp *)(oip + 1);
1094 if (((options & F_VERBOSE) && uid == 0) ||
1095 (!(options & F_QUIET2) &&
1096 (oip->ip_dst.s_addr == whereto.sin_addr.s_addr) &&
1097 (oip->ip_p == IPPROTO_ICMP) &&
1098 (oicmp->icmp_type == ICMP_ECHO) &&
1099 (oicmp->icmp_id == ident))) {
1100 printf("%d bytes from %s: ", cc,
1101 pr_addr(from->sin_addr));
1107 /* Display any IP options */
1108 cp = (u_char *)buf + sizeof(struct ip);
1110 for (; hlen > (int)sizeof(struct ip); --hlen, ++cp)
1117 printf(*cp == IPOPT_LSRR ?
1118 "\nLSRR: " : "\nSSRR: ");
1119 j = cp[IPOPT_OLEN] - IPOPT_MINOFF + 1;
1122 if (j >= INADDR_LEN &&
1123 j <= hlen - (int)sizeof(struct ip)) {
1125 bcopy(++cp, &ina.s_addr, INADDR_LEN);
1126 if (ina.s_addr == 0)
1127 printf("\t0.0.0.0");
1129 printf("\t%s", pr_addr(ina));
1131 cp += INADDR_LEN - 1;
1138 printf("\t(truncated route)\n");
1141 j = cp[IPOPT_OLEN]; /* get length */
1142 i = cp[IPOPT_OFFSET]; /* and pointer */
1147 i = i - IPOPT_MINOFF + 1;
1148 if (i < 0 || i > (hlen - (int)sizeof(struct ip))) {
1153 && !bcmp((char *)cp, old_rr, i)
1154 && !(options & F_FLOOD)) {
1155 printf("\t(same route)");
1161 bcopy((char *)cp, old_rr, i);
1163 if (i >= INADDR_LEN &&
1164 i <= hlen - (int)sizeof(struct ip)) {
1166 bcopy(++cp, &ina.s_addr, INADDR_LEN);
1167 if (ina.s_addr == 0)
1168 printf("\t0.0.0.0");
1170 printf("\t%s", pr_addr(ina));
1172 cp += INADDR_LEN - 1;
1179 printf("\t(truncated route)");
1185 printf("\nunknown option %x", *cp);
1188 if (!(options & F_FLOOD)) {
1196 * Checksum routine for Internet Protocol family headers (C Version)
1199 in_cksum(u_short *addr, int len)
1214 * Our algorithm is simple, using a 32 bit accumulator (sum), we add
1215 * sequential 16 bit words to it, and at the end, fold back all the
1216 * carry bits from the top 16 bits into the lower 16 bits.
1223 /* mop up an odd byte, if necessary */
1225 last.uc[0] = *(u_char *)w;
1230 /* add back carry outs from top 16 bits to low 16 bits */
1231 sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */
1232 sum += (sum >> 16); /* add carry */
1233 answer = ~sum; /* truncate to 16 bits */
1239 * Subtract 2 timeval structs: out = out - in. Out is assumed to
1243 tvsub(struct timeval *out, struct timeval *in)
1246 if ((out->tv_usec -= in->tv_usec) < 0) {
1248 out->tv_usec += 1000000;
1250 out->tv_sec -= in->tv_sec;
1255 * Print out statistics when SIGINFO is received.
1259 status(int sig __unused)
1271 fprintf(stderr, "\r%ld/%ld packets received (%.1f%%)",
1272 nreceived, ntransmitted,
1273 ntransmitted ? nreceived * 100.0 / ntransmitted : 0.0);
1274 if (nreceived && timing)
1275 fprintf(stderr, " %.3f min / %.3f avg / %.3f max",
1276 tmin, tsum / (nreceived + nrepeats), tmax);
1277 fprintf(stderr, "\n");
1283 * Print out statistics, and give up.
1289 signal(SIGINT, SIG_IGN);
1290 signal(SIGALRM, SIG_IGN);
1293 printf("--- %s ping statistics ---\n", hostname);
1294 printf("%ld packets transmitted, ", ntransmitted);
1295 printf("%ld packets received, ", nreceived);
1297 printf("+%ld duplicates, ", nrepeats);
1299 if (nreceived > ntransmitted)
1300 printf("-- somebody's printing up packets!");
1302 printf("%.1f%% packet loss",
1303 ((ntransmitted - nreceived) * 100.0) /
1307 printf(", %ld packets out of wait time", nrcvtimeout);
1309 if (nreceived && timing) {
1310 double n = nreceived + nrepeats;
1311 double avg = tsum / n;
1312 double vari = tsumsq / n - avg * avg;
1314 "round-trip min/avg/max/stddev = %.3f/%.3f/%.3f/%.3f ms\n",
1315 tmin, avg, tmax, sqrt(vari));
1325 static char *ttab[] = {
1326 "Echo Reply", /* ip + seq + udata */
1327 "Dest Unreachable", /* net, host, proto, port, frag, sr + IP */
1328 "Source Quench", /* IP */
1329 "Redirect", /* redirect type, gateway, + IP */
1331 "Time Exceeded", /* transit, frag reassem + IP */
1332 "Parameter Problem", /* pointer + IP */
1333 "Timestamp", /* id + seq + three timestamps */
1334 "Timestamp Reply", /* " */
1335 "Info Request", /* id + sq */
1336 "Info Reply" /* " */
1342 * Print a descriptive string about an ICMP header.
1345 pr_icmph(struct icmp *icp)
1348 switch(icp->icmp_type) {
1349 case ICMP_ECHOREPLY:
1350 printf("Echo Reply\n");
1351 /* XXX ID + Seq + Data */
1354 switch(icp->icmp_code) {
1355 case ICMP_UNREACH_NET:
1356 printf("Destination Net Unreachable\n");
1358 case ICMP_UNREACH_HOST:
1359 printf("Destination Host Unreachable\n");
1361 case ICMP_UNREACH_PROTOCOL:
1362 printf("Destination Protocol Unreachable\n");
1364 case ICMP_UNREACH_PORT:
1365 printf("Destination Port Unreachable\n");
1367 case ICMP_UNREACH_NEEDFRAG:
1368 printf("frag needed and DF set (MTU %d)\n",
1369 ntohs(icp->icmp_nextmtu));
1371 case ICMP_UNREACH_SRCFAIL:
1372 printf("Source Route Failed\n");
1374 case ICMP_UNREACH_FILTER_PROHIB:
1375 printf("Communication prohibited by filter\n");
1378 printf("Dest Unreachable, Bad Code: %d\n",
1382 /* Print returned IP header information */
1384 pr_retip(&icp->icmp_ip);
1386 pr_retip((struct ip *)icp->icmp_data);
1389 case ICMP_SOURCEQUENCH:
1390 printf("Source Quench\n");
1392 pr_retip(&icp->icmp_ip);
1394 pr_retip((struct ip *)icp->icmp_data);
1398 switch(icp->icmp_code) {
1399 case ICMP_REDIRECT_NET:
1400 printf("Redirect Network");
1402 case ICMP_REDIRECT_HOST:
1403 printf("Redirect Host");
1405 case ICMP_REDIRECT_TOSNET:
1406 printf("Redirect Type of Service and Network");
1408 case ICMP_REDIRECT_TOSHOST:
1409 printf("Redirect Type of Service and Host");
1412 printf("Redirect, Bad Code: %d", icp->icmp_code);
1415 printf("(New addr: %s)\n", inet_ntoa(icp->icmp_gwaddr));
1417 pr_retip(&icp->icmp_ip);
1419 pr_retip((struct ip *)icp->icmp_data);
1423 printf("Echo Request\n");
1424 /* XXX ID + Seq + Data */
1427 switch(icp->icmp_code) {
1428 case ICMP_TIMXCEED_INTRANS:
1429 printf("Time to live exceeded\n");
1431 case ICMP_TIMXCEED_REASS:
1432 printf("Frag reassembly time exceeded\n");
1435 printf("Time exceeded, Bad Code: %d\n",
1440 pr_retip(&icp->icmp_ip);
1442 pr_retip((struct ip *)icp->icmp_data);
1445 case ICMP_PARAMPROB:
1446 printf("Parameter problem: pointer = 0x%02x\n",
1447 icp->icmp_hun.ih_pptr);
1449 pr_retip(&icp->icmp_ip);
1451 pr_retip((struct ip *)icp->icmp_data);
1455 printf("Timestamp\n");
1456 /* XXX ID + Seq + 3 timestamps */
1458 case ICMP_TSTAMPREPLY:
1459 printf("Timestamp Reply\n");
1460 /* XXX ID + Seq + 3 timestamps */
1463 printf("Information Request\n");
1466 case ICMP_IREQREPLY:
1467 printf("Information Reply\n");
1471 printf("Address Mask Request\n");
1473 case ICMP_MASKREPLY:
1474 printf("Address Mask Reply\n");
1476 case ICMP_ROUTERADVERT:
1477 printf("Router Advertisement\n");
1479 case ICMP_ROUTERSOLICIT:
1480 printf("Router Solicitation\n");
1483 printf("Bad ICMP type: %d\n", icp->icmp_type);
1489 * Print an IP header with options.
1492 pr_iph(struct ip *ip)
1497 hlen = ip->ip_hl << 2;
1498 cp = (u_char *)ip + 20; /* point to options */
1500 printf("Vr HL TOS Len ID Flg off TTL Pro cks Src Dst\n");
1501 printf(" %1x %1x %02x %04x %04x",
1502 ip->ip_v, ip->ip_hl, ip->ip_tos, ntohs(ip->ip_len),
1504 printf(" %1lx %04lx",
1505 (u_long) (ntohl(ip->ip_off) & 0xe000) >> 13,
1506 (u_long) ntohl(ip->ip_off) & 0x1fff);
1507 printf(" %02x %02x %04x", ip->ip_ttl, ip->ip_p, ntohs(ip->ip_sum));
1508 printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_src.s_addr));
1509 printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_dst.s_addr));
1510 /* dump any option bytes */
1511 while (hlen-- > 20) {
1512 printf("%02x", *cp++);
1519 * Return an ascii host address as a dotted quad and optionally with
1523 pr_addr(struct in_addr ina)
1526 static char buf[16 + 3 + MAXHOSTNAMELEN];
1528 if ((options & F_NUMERIC) ||
1529 !(hp = gethostbyaddr(&ina, 4, AF_INET)))
1530 return inet_ntoa(ina);
1532 snprintf(buf, sizeof(buf), "%s (%s)", hp->h_name,
1539 * Dump some info on a returned (via ICMP) IP packet.
1542 pr_retip(struct ip *ip)
1548 hlen = ip->ip_hl << 2;
1549 cp = (u_char *)ip + hlen;
1552 printf("TCP: from port %u, to port %u (decimal)\n",
1553 (*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3)));
1554 else if (ip->ip_p == 17)
1555 printf("UDP: from port %u, to port %u (decimal)\n",
1556 (*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3)));
1560 pr_ntime (n_time timestamp)
1562 static char buf[10];
1565 sec = ntohl(timestamp) / 1000;
1566 hour = sec / 60 / 60;
1567 min = (sec % (60 * 60)) / 60;
1568 sec = (sec % (60 * 60)) % 60;
1570 snprintf(buf, sizeof(buf), "%02d:%02d:%02d", hour, min, sec);
1576 fill(char *bp, char *patp)
1582 for (cp = patp; *cp; cp++) {
1585 "patterns must be specified as hex digits");
1589 "%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x",
1590 &pat[0], &pat[1], &pat[2], &pat[3], &pat[4], &pat[5], &pat[6],
1591 &pat[7], &pat[8], &pat[9], &pat[10], &pat[11], &pat[12],
1592 &pat[13], &pat[14], &pat[15]);
1595 for (kk = 0; kk <= maxpayload - (TIMEVAL_LEN + ii); kk += ii)
1596 for (jj = 0; jj < ii; ++jj)
1597 bp[jj + kk] = pat[jj];
1598 if (!(options & F_QUIET)) {
1599 printf("PATTERN: 0x");
1600 for (jj = 0; jj < ii; ++jj)
1601 printf("%02x", bp[jj] & 0xFF);
1610 fprintf(stderr, "%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n",
1611 "usage: ping [-AaDdfnoQqRrv] [-c count] [-G sweepmaxsize] [-g sweepminsize]",
1612 " [-h sweepincrsize] [-i wait] [-l preload] [-M mask | time] [-m ttl]",
1613 " [-p pattern] [-S src_addr] [-s packetsize] [-t timeout]",
1614 " [-W waittime] [-z tos] host",
1615 " ping [-AaDdfLnoQqRrv] [-c count] [-I iface] [-i wait] [-l preload]",
1616 " [-M mask | time] [-m ttl] [-p pattern] [-S src_addr]",
1617 " [-s packetsize] [-T ttl] [-t timeout] [-W waittime]",
1618 " [-z tos] mcast-group");