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 * 4. 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
35 static const char copyright[] =
36 "@(#) Copyright (c) 1989, 1993\n\
37 The Regents of the University of California. All rights reserved.\n";
41 static char sccsid[] = "@(#)ping.c 8.1 (Berkeley) 6/5/93";
44 #include <sys/cdefs.h>
45 __FBSDID("$FreeBSD$");
50 * Using the Internet Control Message Protocol (ICMP) "ECHO" facility,
51 * measure round-trip-delays and packet loss across network paths.
55 * U. S. Army Ballistic Research Laboratory
59 * Public Domain. Distribution Unlimited.
61 * More statistics could always be gathered.
62 * This program has to run SUID to ROOT to access the ICMP socket.
65 #include <sys/param.h> /* NB: we rely on this for <sys/types.h> */
66 #include <sys/socket.h>
67 #include <sys/sysctl.h>
71 #include <netinet/in.h>
72 #include <netinet/in_systm.h>
73 #include <netinet/ip.h>
74 #include <netinet/ip_icmp.h>
75 #include <netinet/ip_var.h>
76 #include <arpa/inet.h>
79 #include <netinet6/ipsec.h>
94 #define INADDR_LEN ((int)sizeof(in_addr_t))
95 #define TIMEVAL_LEN ((int)sizeof(struct tv32))
96 #define MASK_LEN (ICMP_MASKLEN - ICMP_MINLEN)
97 #define TS_LEN (ICMP_TSLEN - ICMP_MINLEN)
98 #define DEFDATALEN 56 /* default data length */
99 #define FLOOD_BACKOFF 20000 /* usecs to back off if F_FLOOD mode */
100 /* runs out of buffer space */
101 #define MAXIPLEN (sizeof(struct ip) + MAX_IPOPTLEN)
102 #define MAXICMPLEN (ICMP_ADVLENMIN + MAX_IPOPTLEN)
103 #define MAXWAIT 10 /* max seconds to wait for response */
104 #define MAXALARM (60 * 60) /* max seconds for alarm timeout */
107 #define A(bit) rcvd_tbl[(bit)>>3] /* identify byte in array */
108 #define B(bit) (1 << ((bit) & 0x07)) /* identify bit in byte */
109 #define SET(bit) (A(bit) |= B(bit))
110 #define CLR(bit) (A(bit) &= (~B(bit)))
111 #define TST(bit) (A(bit) & B(bit))
118 /* various options */
120 #define F_FLOOD 0x0001
121 #define F_INTERVAL 0x0002
122 #define F_NUMERIC 0x0004
123 #define F_PINGFILLED 0x0008
124 #define F_QUIET 0x0010
125 #define F_RROUTE 0x0020
126 #define F_SO_DEBUG 0x0040
127 #define F_SO_DONTROUTE 0x0080
128 #define F_VERBOSE 0x0100
129 #define F_QUIET2 0x0200
130 #define F_NOLOOP 0x0400
131 #define F_MTTL 0x0800
133 #define F_AUDIBLE 0x2000
135 #ifdef IPSEC_POLICY_IPSEC
136 #define F_POLICY 0x4000
137 #endif /*IPSEC_POLICY_IPSEC*/
140 #define F_MISSED 0x10000
141 #define F_ONCE 0x20000
142 #define F_HDRINCL 0x40000
143 #define F_MASK 0x80000
144 #define F_TIME 0x100000
147 * MAX_DUP_CHK is the number of bits in received table, i.e. the maximum
148 * number of received sequence numbers we can keep track of. Change 128
149 * to 8192 for complete accuracy...
151 #define MAX_DUP_CHK (8 * 128)
152 int mx_dup_ck = MAX_DUP_CHK;
153 char rcvd_tbl[MAX_DUP_CHK / 8];
155 struct sockaddr_in whereto; /* who to ping */
156 int datalen = DEFDATALEN;
158 int s; /* socket file descriptor */
159 u_char outpackhdr[IP_MAXPACKET], *outpack;
160 char BBELL = '\a'; /* characters written for MISSED and AUDIBLE */
161 char BSPACE = '\b'; /* characters written for flood */
165 int ident; /* process id to identify our packets */
166 int uid; /* cached uid for micro-optimization */
167 u_char icmp_type = ICMP_ECHO;
168 u_char icmp_type_rsp = ICMP_ECHOREPLY;
173 long nmissedmax; /* max value of ntransmitted - nreceived - 1 */
174 long npackets; /* max packets to transmit */
175 long nreceived; /* # of packets we got back */
176 long nrepeats; /* number of duplicates */
177 long ntransmitted; /* sequence # for outbound packets = #sent */
178 int interval = 1000; /* interval between packets, ms */
181 int timing; /* flag to do timing */
182 double tmin = 999999999.0; /* minimum round trip time */
183 double tmax = 0.0; /* maximum round trip time */
184 double tsum = 0.0; /* sum of all times, for doing average */
185 double tsumsq = 0.0; /* sum of all times squared, for std. dev. */
187 volatile sig_atomic_t finish_up; /* nonzero if we've been told to finish up */
188 volatile sig_atomic_t siginfo_p;
190 static void fill(char *, char *);
191 static u_short in_cksum(u_short *, int);
192 static void check_status(void);
193 static void finish(void) __dead2;
194 static void pinger(void);
195 static char *pr_addr(struct in_addr);
196 static char *pr_ntime(n_time);
197 static void pr_icmph(struct icmp *);
198 static void pr_iph(struct ip *);
199 static void pr_pack(char *, int, struct sockaddr_in *, struct timeval *);
200 static void pr_retip(struct ip *);
201 static void status(int);
202 static void stopit(int);
203 static void tvsub(struct timeval *, struct timeval *);
204 static void usage(void) __dead2;
211 struct sockaddr_in from, sock_in;
212 struct in_addr ifaddr;
213 struct timeval last, intvl;
217 struct sigaction si_sa;
219 u_char *datap, packet[IP_MAXPACKET];
220 char *ep, *source, *target, *payload;
222 #ifdef IPSEC_POLICY_IPSEC
223 char *policy_in, *policy_out;
225 struct sockaddr_in *to;
227 u_long alarmtimeout, ultmp;
228 int almost_done, ch, df, hold, i, icmp_len, mib[4], preload, sockerrno,
230 char ctrl[CMSG_SPACE(sizeof(struct timeval))];
231 char hnamebuf[MAXHOSTNAMELEN], snamebuf[MAXHOSTNAMELEN];
233 char rspace[MAX_IPOPTLEN]; /* record route space */
235 unsigned char loop, mttl;
237 payload = source = NULL;
238 #ifdef IPSEC_POLICY_IPSEC
239 policy_in = policy_out = NULL;
243 * Do the stuff that we need root priv's for *first*, and
244 * then drop our setuid bit. Save error reporting for
247 s = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
253 alarmtimeout = df = preload = tos = 0;
255 outpack = outpackhdr + sizeof(struct ip);
256 while ((ch = getopt(argc, argv,
257 "Aac:DdfI:i:Ll:M:m:nop:QqRrS:s:T:t:vz:"
259 #ifdef IPSEC_POLICY_IPSEC
261 #endif /*IPSEC_POLICY_IPSEC*/
270 options |= F_AUDIBLE;
273 ultmp = strtoul(optarg, &ep, 0);
274 if (*ep || ep == optarg || ultmp > LONG_MAX || !ultmp)
276 "invalid count of packets to transmit: `%s'",
281 options |= F_HDRINCL;
285 options |= F_SO_DEBUG;
290 err(EX_NOPERM, "-f flag");
293 setbuf(stdout, (char *)NULL);
295 case 'I': /* multicast interface */
296 if (inet_aton(optarg, &ifaddr) == 0)
298 "invalid multicast interface: `%s'",
302 case 'i': /* wait between sending packets */
303 t = strtod(optarg, &ep) * 1000.0;
304 if (*ep || ep == optarg || t > (double)INT_MAX)
305 errx(EX_USAGE, "invalid timing interval: `%s'",
307 options |= F_INTERVAL;
309 if (uid && interval < 1000) {
311 err(EX_NOPERM, "-i interval too short");
319 ultmp = strtoul(optarg, &ep, 0);
320 if (*ep || ep == optarg || ultmp > INT_MAX)
322 "invalid preload value: `%s'", optarg);
325 err(EX_NOPERM, "-l flag");
340 errx(EX_USAGE, "invalid message: `%c'", optarg[0]);
345 ultmp = strtoul(optarg, &ep, 0);
346 if (*ep || ep == optarg || ultmp > MAXTTL)
347 errx(EX_USAGE, "invalid TTL: `%s'", optarg);
352 options |= F_NUMERIC;
358 #ifdef IPSEC_POLICY_IPSEC
361 if (!strncmp("in", optarg, 2))
362 policy_in = strdup(optarg);
363 else if (!strncmp("out", optarg, 3))
364 policy_out = strdup(optarg);
366 errx(1, "invalid security policy");
368 #endif /*IPSEC_POLICY_IPSEC*/
370 case 'p': /* fill buffer with user pattern */
371 options |= F_PINGFILLED;
384 options |= F_SO_DONTROUTE;
389 case 's': /* size of packet to send */
390 ultmp = strtoul(optarg, &ep, 0);
391 if (*ep || ep == optarg)
392 errx(EX_USAGE, "invalid packet size: `%s'",
394 if (uid != 0 && ultmp > DEFDATALEN) {
397 "packet size too large: %lu > %u",
402 case 'T': /* multicast TTL */
403 ultmp = strtoul(optarg, &ep, 0);
404 if (*ep || ep == optarg || ultmp > MAXTTL)
405 errx(EX_USAGE, "invalid multicast TTL: `%s'",
411 alarmtimeout = strtoul(optarg, &ep, 0);
412 if ((alarmtimeout < 1) || (alarmtimeout == ULONG_MAX))
413 errx(EX_USAGE, "invalid timeout: `%s'",
415 if (alarmtimeout > MAXALARM)
416 errx(EX_USAGE, "invalid timeout: `%s' > %d",
418 alarm((int)alarmtimeout);
421 options |= F_VERBOSE;
424 options |= F_HDRINCL;
425 ultmp = strtoul(optarg, &ep, 0);
426 if (*ep || ep == optarg || ultmp > MAXTOS)
427 errx(EX_USAGE, "invalid TOS: `%s'", optarg);
435 if (argc - optind != 1)
437 target = argv[optind];
439 switch (options & (F_MASK|F_TIME)) {
442 icmp_type = ICMP_MASKREQ;
443 icmp_type_rsp = ICMP_MASKREPLY;
445 if (!(options & F_QUIET))
446 (void)printf("ICMP_MASKREQ\n");
449 icmp_type = ICMP_TSTAMP;
450 icmp_type_rsp = ICMP_TSTAMPREPLY;
452 if (!(options & F_QUIET))
453 (void)printf("ICMP_TSTAMP\n");
456 errx(EX_USAGE, "ICMP_TSTAMP and ICMP_MASKREQ are exclusive.");
459 icmp_len = sizeof(struct ip) + ICMP_MINLEN + phdr_len;
460 if (options & F_RROUTE)
461 icmp_len += MAX_IPOPTLEN;
462 maxpayload = IP_MAXPACKET - icmp_len;
463 if (datalen > maxpayload)
464 errx(EX_USAGE, "packet size too large: %d > %d", datalen,
466 send_len = icmp_len + datalen;
467 datap = &outpack[ICMP_MINLEN + phdr_len + TIMEVAL_LEN];
468 if (options & F_PINGFILLED) {
469 fill((char *)datap, payload);
472 bzero((char *)&sock_in, sizeof(sock_in));
473 sock_in.sin_family = AF_INET;
474 if (inet_aton(source, &sock_in.sin_addr) != 0) {
477 hp = gethostbyname2(source, AF_INET);
479 errx(EX_NOHOST, "cannot resolve %s: %s",
480 source, hstrerror(h_errno));
482 sock_in.sin_len = sizeof sock_in;
483 if ((unsigned)hp->h_length > sizeof(sock_in.sin_addr) ||
485 errx(1, "gethostbyname2: illegal address");
486 memcpy(&sock_in.sin_addr, hp->h_addr_list[0],
487 sizeof(sock_in.sin_addr));
488 (void)strncpy(snamebuf, hp->h_name,
489 sizeof(snamebuf) - 1);
490 snamebuf[sizeof(snamebuf) - 1] = '\0';
491 shostname = snamebuf;
493 if (bind(s, (struct sockaddr *)&sock_in, sizeof sock_in) == -1)
497 bzero(&whereto, sizeof(whereto));
499 to->sin_family = AF_INET;
500 to->sin_len = sizeof *to;
501 if (inet_aton(target, &to->sin_addr) != 0) {
504 hp = gethostbyname2(target, AF_INET);
506 errx(EX_NOHOST, "cannot resolve %s: %s",
507 target, hstrerror(h_errno));
509 if ((unsigned)hp->h_length > sizeof(to->sin_addr))
510 errx(1, "gethostbyname2 returned an illegal address");
511 memcpy(&to->sin_addr, hp->h_addr_list[0], sizeof to->sin_addr);
512 (void)strncpy(hnamebuf, hp->h_name, sizeof(hnamebuf) - 1);
513 hnamebuf[sizeof(hnamebuf) - 1] = '\0';
517 if (options & F_FLOOD && options & F_INTERVAL)
518 errx(EX_USAGE, "-f and -i: incompatible options");
520 if (options & F_FLOOD && IN_MULTICAST(ntohl(to->sin_addr.s_addr)))
522 "-f flag cannot be used with multicast destination");
523 if (options & (F_MIF | F_NOLOOP | F_MTTL)
524 && !IN_MULTICAST(ntohl(to->sin_addr.s_addr)))
526 "-I, -L, -T flags cannot be used with unicast destination");
528 if (datalen >= TIMEVAL_LEN) /* can we time transfer */
531 if (!(options & F_PINGFILLED))
532 for (i = TIMEVAL_LEN; i < datalen; ++i)
535 ident = getpid() & 0xFFFF;
539 err(EX_OSERR, "socket");
542 if (options & F_SO_DEBUG)
543 (void)setsockopt(s, SOL_SOCKET, SO_DEBUG, (char *)&hold,
545 if (options & F_SO_DONTROUTE)
546 (void)setsockopt(s, SOL_SOCKET, SO_DONTROUTE, (char *)&hold,
549 #ifdef IPSEC_POLICY_IPSEC
550 if (options & F_POLICY) {
552 if (policy_in != NULL) {
553 buf = ipsec_set_policy(policy_in, strlen(policy_in));
555 errx(EX_CONFIG, "%s", ipsec_strerror());
556 if (setsockopt(s, IPPROTO_IP, IP_IPSEC_POLICY,
557 buf, ipsec_get_policylen(buf)) < 0)
559 "ipsec policy cannot be configured");
563 if (policy_out != NULL) {
564 buf = ipsec_set_policy(policy_out, strlen(policy_out));
566 errx(EX_CONFIG, "%s", ipsec_strerror());
567 if (setsockopt(s, IPPROTO_IP, IP_IPSEC_POLICY,
568 buf, ipsec_get_policylen(buf)) < 0)
570 "ipsec policy cannot be configured");
574 #endif /*IPSEC_POLICY_IPSEC*/
577 if (options & F_HDRINCL) {
578 ip = (struct ip*)outpackhdr;
579 if (!(options & (F_TTL | F_MTTL))) {
583 mib[3] = IPCTL_DEFTTL;
585 if (sysctl(mib, 4, &ttl, &sz, NULL, 0) == -1)
586 err(1, "sysctl(net.inet.ip.ttl)");
588 setsockopt(s, IPPROTO_IP, IP_HDRINCL, &hold, sizeof(hold));
589 ip->ip_v = IPVERSION;
590 ip->ip_hl = sizeof(struct ip) >> 2;
593 ip->ip_off = df ? IP_DF : 0;
595 ip->ip_p = IPPROTO_ICMP;
596 ip->ip_src.s_addr = source ? sock_in.sin_addr.s_addr : INADDR_ANY;
597 ip->ip_dst = to->sin_addr;
599 /* record route option */
600 if (options & F_RROUTE) {
602 bzero(rspace, sizeof(rspace));
603 rspace[IPOPT_OPTVAL] = IPOPT_RR;
604 rspace[IPOPT_OLEN] = sizeof(rspace) - 1;
605 rspace[IPOPT_OFFSET] = IPOPT_MINOFF;
606 rspace[sizeof(rspace) - 1] = IPOPT_EOL;
607 if (setsockopt(s, IPPROTO_IP, IP_OPTIONS, rspace,
609 err(EX_OSERR, "setsockopt IP_OPTIONS");
612 "record route not available in this implementation");
613 #endif /* IP_OPTIONS */
616 if (options & F_TTL) {
617 if (setsockopt(s, IPPROTO_IP, IP_TTL, &ttl,
619 err(EX_OSERR, "setsockopt IP_TTL");
622 if (options & F_NOLOOP) {
623 if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_LOOP, &loop,
625 err(EX_OSERR, "setsockopt IP_MULTICAST_LOOP");
628 if (options & F_MTTL) {
629 if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL, &mttl,
631 err(EX_OSERR, "setsockopt IP_MULTICAST_TTL");
634 if (options & F_MIF) {
635 if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_IF, &ifaddr,
636 sizeof(ifaddr)) < 0) {
637 err(EX_OSERR, "setsockopt IP_MULTICAST_IF");
642 if (setsockopt(s, SOL_SOCKET, SO_TIMESTAMP, &on, sizeof(on)) < 0)
643 err(EX_OSERR, "setsockopt SO_TIMESTAMP");
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 (void)setsockopt(s, SOL_SOCKET, SO_RCVBUF, (char *)&hold,
663 (void)setsockopt(s, SOL_SOCKET, SO_SNDBUF, (char *)&hold,
666 if (to->sin_family == AF_INET) {
667 (void)printf("PING %s (%s)", hostname,
668 inet_ntoa(to->sin_addr));
670 (void)printf(" from %s", shostname);
671 (void)printf(": %d data bytes\n", datalen);
673 (void)printf("PING %s: %d data bytes\n", hostname, datalen);
676 * Use sigaction() instead of signal() to get unambiguous semantics,
677 * in particular with SA_RESTART not set.
680 sigemptyset(&si_sa.sa_mask);
683 si_sa.sa_handler = stopit;
684 if (sigaction(SIGINT, &si_sa, 0) == -1) {
685 err(EX_OSERR, "sigaction SIGINT");
688 si_sa.sa_handler = status;
689 if (sigaction(SIGINFO, &si_sa, 0) == -1) {
690 err(EX_OSERR, "sigaction");
693 if (alarmtimeout > 0) {
694 si_sa.sa_handler = stopit;
695 if (sigaction(SIGALRM, &si_sa, 0) == -1)
696 err(EX_OSERR, "sigaction SIGALRM");
699 bzero(&msg, sizeof(msg));
700 msg.msg_name = (caddr_t)&from;
704 msg.msg_control = (caddr_t)ctrl;
706 iov.iov_base = packet;
707 iov.iov_len = IP_MAXPACKET;
710 pinger(); /* send the first ping */
712 if (npackets != 0 && preload > npackets)
714 while (preload--) /* fire off them quickies */
717 (void)gettimeofday(&last, NULL);
719 if (options & F_FLOOD) {
721 intvl.tv_usec = 10000;
723 intvl.tv_sec = interval / 1000;
724 intvl.tv_usec = interval % 1000 * 1000;
729 struct timeval now, timeout;
734 if ((unsigned)s >= FD_SETSIZE)
735 errx(EX_OSERR, "descriptor too large");
738 (void)gettimeofday(&now, NULL);
739 timeout.tv_sec = last.tv_sec + intvl.tv_sec - now.tv_sec;
740 timeout.tv_usec = last.tv_usec + intvl.tv_usec - now.tv_usec;
741 while (timeout.tv_usec < 0) {
742 timeout.tv_usec += 1000000;
745 while (timeout.tv_usec >= 1000000) {
746 timeout.tv_usec -= 1000000;
749 if (timeout.tv_sec < 0)
750 timeout.tv_sec = timeout.tv_usec = 0;
751 n = select(s + 1, &rfds, NULL, NULL, &timeout);
753 continue; /* Must be EINTR. */
755 struct timeval *tv = NULL;
757 struct cmsghdr *cmsg = (struct cmsghdr *)&ctrl;
759 msg.msg_controllen = sizeof(ctrl);
761 msg.msg_namelen = sizeof(from);
762 if ((cc = recvmsg(s, &msg, 0)) < 0) {
769 if (cmsg->cmsg_level == SOL_SOCKET &&
770 cmsg->cmsg_type == SCM_TIMESTAMP &&
771 cmsg->cmsg_len == CMSG_LEN(sizeof *tv)) {
772 /* Copy to avoid alignment problems: */
773 memcpy(&now, CMSG_DATA(cmsg), sizeof(now));
778 (void)gettimeofday(&now, NULL);
781 pr_pack((char *)packet, cc, &from, tv);
782 if ((options & F_ONCE && nreceived) ||
783 (npackets && nreceived >= npackets))
786 if (n == 0 || options & F_FLOOD) {
787 if (!npackets || ntransmitted < npackets)
795 intvl.tv_sec = 2 * tmax / 1000;
799 intvl.tv_sec = MAXWAIT;
801 (void)gettimeofday(&last, NULL);
802 if (ntransmitted - nreceived - 1 > nmissedmax) {
803 nmissedmax = ntransmitted - nreceived - 1;
804 if (options & F_MISSED)
805 (void)write(STDOUT_FILENO, &BBELL, 1);
811 exit(0); /* Make the compiler happy */
816 * Set the global bit that causes the main loop to quit.
817 * Do NOT call finish() from here, since finish() does far too much
818 * to be called from a signal handler.
826 * When doing reverse DNS lookups, the finish_up flag might not
827 * be noticed for a while. Just exit if we get a second SIGINT.
829 if (!(options & F_NUMERIC) && finish_up)
830 _exit(nreceived ? 0 : 2);
836 * Compose and transmit an ICMP ECHO REQUEST packet. The IP packet
837 * will be added on by the kernel. The ID field is our UNIX process ID,
838 * and the sequence number is an ascending integer. The first TIMEVAL_LEN
839 * bytes of the data portion are used to hold a UNIX "timeval" struct in
840 * host byte-order, to compute the round-trip time.
853 icp = (struct icmp *)outpack;
854 icp->icmp_type = icmp_type;
857 icp->icmp_seq = htons(ntransmitted);
858 icp->icmp_id = ident; /* ID */
860 CLR(ntransmitted % mx_dup_ck);
862 if ((options & F_TIME) || timing) {
863 (void)gettimeofday(&now, NULL);
865 tv32.tv32_sec = htonl(now.tv_sec);
866 tv32.tv32_usec = htonl(now.tv_usec);
867 if (options & F_TIME)
868 icp->icmp_otime = htonl((now.tv_sec % (24*60*60))
869 * 1000 + now.tv_usec / 1000);
872 (void *)&outpack[ICMP_MINLEN + phdr_len],
876 cc = ICMP_MINLEN + phdr_len + datalen;
878 /* compute ICMP checksum here */
879 icp->icmp_cksum = in_cksum((u_short *)icp, cc);
881 if (options & F_HDRINCL) {
882 cc += sizeof(struct ip);
883 ip = (struct ip *)outpackhdr;
885 ip->ip_sum = in_cksum((u_short *)outpackhdr, cc);
888 i = sendto(s, (char *)packet, cc, 0, (struct sockaddr *)&whereto,
891 if (i < 0 || i != cc) {
893 if (options & F_FLOOD && errno == ENOBUFS) {
894 usleep(FLOOD_BACKOFF);
899 warn("%s: partial write: %d of %d bytes",
904 if (!(options & F_QUIET) && options & F_FLOOD)
905 (void)write(STDOUT_FILENO, &DOT, 1);
910 * Print out the packet, if it came from us. This logic is necessary
911 * because ALL readers of the ICMP socket get a copy of ALL ICMP packets
912 * which arrive ('tis only fair). This permits multiple copies of this
913 * program to be run without having intermingled output (or statistics!).
916 pr_pack(buf, cc, from, tv)
919 struct sockaddr_in *from;
928 int dupflag, hlen, i, j, recv_len, seq;
929 static int old_rrlen;
930 static char old_rr[MAX_IPOPTLEN];
932 /* Check the IP header */
933 ip = (struct ip *)buf;
934 hlen = ip->ip_hl << 2;
936 if (cc < hlen + ICMP_MINLEN) {
937 if (options & F_VERBOSE)
938 warn("packet too short (%d bytes) from %s", cc,
939 inet_ntoa(from->sin_addr));
943 /* Now the ICMP part */
945 icp = (struct icmp *)(buf + hlen);
946 if (icp->icmp_type == icmp_type_rsp) {
947 if (icp->icmp_id != ident)
948 return; /* 'Twas not our ECHO */
959 tp = (const char *)tp + phdr_len;
961 if (cc - ICMP_MINLEN - phdr_len >= sizeof(tv1)) {
962 /* Copy to avoid alignment problems: */
963 memcpy(&tv32, tp, sizeof(tv32));
964 tv1.tv_sec = ntohl(tv32.tv32_sec);
965 tv1.tv_usec = ntohl(tv32.tv32_usec);
967 triptime = ((double)tv->tv_sec) * 1000.0 +
968 ((double)tv->tv_usec) / 1000.0;
970 tsumsq += triptime * triptime;
979 seq = ntohs(icp->icmp_seq);
981 if (TST(seq % mx_dup_ck)) {
986 SET(seq % mx_dup_ck);
990 if (options & F_QUIET)
993 if (options & F_FLOOD)
994 (void)write(STDOUT_FILENO, &BSPACE, 1);
996 (void)printf("%d bytes from %s: icmp_seq=%u", cc,
997 inet_ntoa(*(struct in_addr *)&from->sin_addr.s_addr),
999 (void)printf(" ttl=%d", ip->ip_ttl);
1001 (void)printf(" time=%.3f ms", triptime);
1003 (void)printf(" (DUP!)");
1004 if (options & F_AUDIBLE)
1005 (void)write(STDOUT_FILENO, &BBELL, 1);
1006 if (options & F_MASK) {
1007 /* Just prentend this cast isn't ugly */
1008 (void)printf(" mask=%s",
1009 pr_addr(*(struct in_addr *)&(icp->icmp_mask)));
1011 if (options & F_TIME) {
1012 (void)printf(" tso=%s", pr_ntime(icp->icmp_otime));
1013 (void)printf(" tsr=%s", pr_ntime(icp->icmp_rtime));
1014 (void)printf(" tst=%s", pr_ntime(icp->icmp_ttime));
1016 if (recv_len != send_len) {
1018 "\nwrong total length %d instead of %d",
1019 recv_len, send_len);
1021 /* check the data */
1022 cp = (u_char*)&icp->icmp_data[phdr_len];
1023 dp = &outpack[ICMP_MINLEN + phdr_len];
1024 cc -= ICMP_MINLEN + phdr_len;
1026 if (timing) { /* don't check variable timestamp */
1032 for (; i < datalen && cc > 0; ++i, ++cp, ++dp, --cc) {
1034 (void)printf("\nwrong data byte #%d should be 0x%x but was 0x%x",
1036 (void)printf("\ncp:");
1037 cp = (u_char*)&icp->icmp_data[0];
1038 for (i = 0; i < datalen; ++i, ++cp) {
1040 (void)printf("\n\t");
1041 (void)printf("%2x ", *cp);
1043 (void)printf("\ndp:");
1044 cp = &outpack[ICMP_MINLEN];
1045 for (i = 0; i < datalen; ++i, ++cp) {
1047 (void)printf("\n\t");
1048 (void)printf("%2x ", *cp);
1056 * We've got something other than an ECHOREPLY.
1057 * See if it's a reply to something that we sent.
1058 * We can compare IP destination, protocol,
1059 * and ICMP type and ID.
1061 * Only print all the error messages if we are running
1062 * as root to avoid leaking information not normally
1063 * available to those not running as root.
1066 struct ip *oip = &icp->icmp_ip;
1068 struct ip *oip = (struct ip *)icp->icmp_data;
1070 struct icmp *oicmp = (struct icmp *)(oip + 1);
1072 if (((options & F_VERBOSE) && uid == 0) ||
1073 (!(options & F_QUIET2) &&
1074 (oip->ip_dst.s_addr == whereto.sin_addr.s_addr) &&
1075 (oip->ip_p == IPPROTO_ICMP) &&
1076 (oicmp->icmp_type == ICMP_ECHO) &&
1077 (oicmp->icmp_id == ident))) {
1078 (void)printf("%d bytes from %s: ", cc,
1079 pr_addr(from->sin_addr));
1085 /* Display any IP options */
1086 cp = (u_char *)buf + sizeof(struct ip);
1088 for (; hlen > (int)sizeof(struct ip); --hlen, ++cp)
1095 (void)printf(*cp == IPOPT_LSRR ?
1096 "\nLSRR: " : "\nSSRR: ");
1097 j = cp[IPOPT_OLEN] - IPOPT_MINOFF + 1;
1100 if (j >= INADDR_LEN &&
1101 j <= hlen - (int)sizeof(struct ip)) {
1103 bcopy(++cp, &ina.s_addr, INADDR_LEN);
1104 if (ina.s_addr == 0)
1105 (void)printf("\t0.0.0.0");
1107 (void)printf("\t%s",
1110 cp += INADDR_LEN - 1;
1114 (void)putchar('\n');
1117 (void)printf("\t(truncated route)\n");
1120 j = cp[IPOPT_OLEN]; /* get length */
1121 i = cp[IPOPT_OFFSET]; /* and pointer */
1126 i = i - IPOPT_MINOFF + 1;
1127 if (i < 0 || i > (hlen - (int)sizeof(struct ip))) {
1132 && !bcmp((char *)cp, old_rr, i)
1133 && !(options & F_FLOOD)) {
1134 (void)printf("\t(same route)");
1140 bcopy((char *)cp, old_rr, i);
1141 (void)printf("\nRR: ");
1142 if (i >= INADDR_LEN &&
1143 i <= hlen - (int)sizeof(struct ip)) {
1145 bcopy(++cp, &ina.s_addr, INADDR_LEN);
1146 if (ina.s_addr == 0)
1147 (void)printf("\t0.0.0.0");
1149 (void)printf("\t%s",
1152 cp += INADDR_LEN - 1;
1156 (void)putchar('\n');
1159 (void)printf("\t(truncated route)");
1162 (void)printf("\nNOP");
1165 (void)printf("\nunknown option %x", *cp);
1168 if (!(options & F_FLOOD)) {
1169 (void)putchar('\n');
1170 (void)fflush(stdout);
1176 * Checksum routine for Internet Protocol family headers (C Version)
1196 * Our algorithm is simple, using a 32 bit accumulator (sum), we add
1197 * sequential 16 bit words to it, and at the end, fold back all the
1198 * carry bits from the top 16 bits into the lower 16 bits.
1205 /* mop up an odd byte, if necessary */
1207 last.uc[0] = *(u_char *)w;
1212 /* add back carry outs from top 16 bits to low 16 bits */
1213 sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */
1214 sum += (sum >> 16); /* add carry */
1215 answer = ~sum; /* truncate to 16 bits */
1221 * Subtract 2 timeval structs: out = out - in. Out is assumed to
1226 struct timeval *out, *in;
1229 if ((out->tv_usec -= in->tv_usec) < 0) {
1231 out->tv_usec += 1000000;
1233 out->tv_sec -= in->tv_sec;
1238 * Print out statistics when SIGINFO is received.
1255 (void)fprintf(stderr, "\r%ld/%ld packets received (%.0f%%)",
1256 nreceived, ntransmitted,
1257 ntransmitted ? nreceived * 100.0 / ntransmitted : 0.0);
1258 if (nreceived && timing)
1259 (void)fprintf(stderr, " %.3f min / %.3f avg / %.3f max",
1260 tmin, tsum / (nreceived + nrepeats), tmax);
1261 (void)fprintf(stderr, "\n");
1267 * Print out statistics, and give up.
1273 (void)signal(SIGINT, SIG_IGN);
1274 (void)signal(SIGALRM, SIG_IGN);
1275 (void)putchar('\n');
1276 (void)fflush(stdout);
1277 (void)printf("--- %s ping statistics ---\n", hostname);
1278 (void)printf("%ld packets transmitted, ", ntransmitted);
1279 (void)printf("%ld packets received, ", nreceived);
1281 (void)printf("+%ld duplicates, ", nrepeats);
1283 if (nreceived > ntransmitted)
1284 (void)printf("-- somebody's printing up packets!");
1286 (void)printf("%d%% packet loss",
1287 (int)(((ntransmitted - nreceived) * 100) /
1290 (void)putchar('\n');
1291 if (nreceived && timing) {
1292 double n = nreceived + nrepeats;
1293 double avg = tsum / n;
1294 double vari = tsumsq / n - avg * avg;
1296 "round-trip min/avg/max/stddev = %.3f/%.3f/%.3f/%.3f ms\n",
1297 tmin, avg, tmax, sqrt(vari));
1307 static char *ttab[] = {
1308 "Echo Reply", /* ip + seq + udata */
1309 "Dest Unreachable", /* net, host, proto, port, frag, sr + IP */
1310 "Source Quench", /* IP */
1311 "Redirect", /* redirect type, gateway, + IP */
1313 "Time Exceeded", /* transit, frag reassem + IP */
1314 "Parameter Problem", /* pointer + IP */
1315 "Timestamp", /* id + seq + three timestamps */
1316 "Timestamp Reply", /* " */
1317 "Info Request", /* id + sq */
1318 "Info Reply" /* " */
1324 * Print a descriptive string about an ICMP header.
1331 switch(icp->icmp_type) {
1332 case ICMP_ECHOREPLY:
1333 (void)printf("Echo Reply\n");
1334 /* XXX ID + Seq + Data */
1337 switch(icp->icmp_code) {
1338 case ICMP_UNREACH_NET:
1339 (void)printf("Destination Net Unreachable\n");
1341 case ICMP_UNREACH_HOST:
1342 (void)printf("Destination Host Unreachable\n");
1344 case ICMP_UNREACH_PROTOCOL:
1345 (void)printf("Destination Protocol Unreachable\n");
1347 case ICMP_UNREACH_PORT:
1348 (void)printf("Destination Port Unreachable\n");
1350 case ICMP_UNREACH_NEEDFRAG:
1351 (void)printf("frag needed and DF set (MTU %d)\n",
1352 ntohs(icp->icmp_nextmtu));
1354 case ICMP_UNREACH_SRCFAIL:
1355 (void)printf("Source Route Failed\n");
1357 case ICMP_UNREACH_FILTER_PROHIB:
1358 (void)printf("Communication prohibited by filter\n");
1361 (void)printf("Dest Unreachable, Bad Code: %d\n",
1365 /* Print returned IP header information */
1367 pr_retip(&icp->icmp_ip);
1369 pr_retip((struct ip *)icp->icmp_data);
1372 case ICMP_SOURCEQUENCH:
1373 (void)printf("Source Quench\n");
1375 pr_retip(&icp->icmp_ip);
1377 pr_retip((struct ip *)icp->icmp_data);
1381 switch(icp->icmp_code) {
1382 case ICMP_REDIRECT_NET:
1383 (void)printf("Redirect Network");
1385 case ICMP_REDIRECT_HOST:
1386 (void)printf("Redirect Host");
1388 case ICMP_REDIRECT_TOSNET:
1389 (void)printf("Redirect Type of Service and Network");
1391 case ICMP_REDIRECT_TOSHOST:
1392 (void)printf("Redirect Type of Service and Host");
1395 (void)printf("Redirect, Bad Code: %d", icp->icmp_code);
1398 (void)printf("(New addr: %s)\n", inet_ntoa(icp->icmp_gwaddr));
1400 pr_retip(&icp->icmp_ip);
1402 pr_retip((struct ip *)icp->icmp_data);
1406 (void)printf("Echo Request\n");
1407 /* XXX ID + Seq + Data */
1410 switch(icp->icmp_code) {
1411 case ICMP_TIMXCEED_INTRANS:
1412 (void)printf("Time to live exceeded\n");
1414 case ICMP_TIMXCEED_REASS:
1415 (void)printf("Frag reassembly time exceeded\n");
1418 (void)printf("Time exceeded, Bad Code: %d\n",
1423 pr_retip(&icp->icmp_ip);
1425 pr_retip((struct ip *)icp->icmp_data);
1428 case ICMP_PARAMPROB:
1429 (void)printf("Parameter problem: pointer = 0x%02x\n",
1430 icp->icmp_hun.ih_pptr);
1432 pr_retip(&icp->icmp_ip);
1434 pr_retip((struct ip *)icp->icmp_data);
1438 (void)printf("Timestamp\n");
1439 /* XXX ID + Seq + 3 timestamps */
1441 case ICMP_TSTAMPREPLY:
1442 (void)printf("Timestamp Reply\n");
1443 /* XXX ID + Seq + 3 timestamps */
1446 (void)printf("Information Request\n");
1449 case ICMP_IREQREPLY:
1450 (void)printf("Information Reply\n");
1454 (void)printf("Address Mask Request\n");
1456 case ICMP_MASKREPLY:
1457 (void)printf("Address Mask Reply\n");
1459 case ICMP_ROUTERADVERT:
1460 (void)printf("Router Advertisement\n");
1462 case ICMP_ROUTERSOLICIT:
1463 (void)printf("Router Solicitation\n");
1466 (void)printf("Bad ICMP type: %d\n", icp->icmp_type);
1472 * Print an IP header with options.
1481 hlen = ip->ip_hl << 2;
1482 cp = (u_char *)ip + 20; /* point to options */
1484 (void)printf("Vr HL TOS Len ID Flg off TTL Pro cks Src Dst\n");
1485 (void)printf(" %1x %1x %02x %04x %04x",
1486 ip->ip_v, ip->ip_hl, ip->ip_tos, ntohs(ip->ip_len),
1488 (void)printf(" %1lx %04lx",
1489 (u_long) (ntohl(ip->ip_off) & 0xe000) >> 13,
1490 (u_long) ntohl(ip->ip_off) & 0x1fff);
1491 (void)printf(" %02x %02x %04x", ip->ip_ttl, ip->ip_p,
1493 (void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_src.s_addr));
1494 (void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_dst.s_addr));
1495 /* dump any option bytes */
1496 while (hlen-- > 20) {
1497 (void)printf("%02x", *cp++);
1499 (void)putchar('\n');
1504 * Return an ascii host address as a dotted quad and optionally with
1512 static char buf[16 + 3 + MAXHOSTNAMELEN];
1514 if ((options & F_NUMERIC) ||
1515 !(hp = gethostbyaddr((char *)&ina, 4, AF_INET)))
1516 return inet_ntoa(ina);
1518 (void)snprintf(buf, sizeof(buf), "%s (%s)", hp->h_name,
1525 * Dump some info on a returned (via ICMP) IP packet.
1535 hlen = ip->ip_hl << 2;
1536 cp = (u_char *)ip + hlen;
1539 (void)printf("TCP: from port %u, to port %u (decimal)\n",
1540 (*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3)));
1541 else if (ip->ip_p == 17)
1542 (void)printf("UDP: from port %u, to port %u (decimal)\n",
1543 (*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3)));
1547 pr_ntime (n_time timestamp)
1549 static char buf[10];
1552 sec = ntohl(timestamp) / 1000;
1553 hour = sec / 60 / 60;
1554 min = (sec % (60 * 60)) / 60;
1555 sec = (sec % (60 * 60)) % 60;
1557 (void)snprintf(buf, sizeof(buf), "%02d:%02d:%02d", hour, min, sec);
1570 for (cp = patp; *cp; cp++) {
1573 "patterns must be specified as hex digits");
1577 "%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x",
1578 &pat[0], &pat[1], &pat[2], &pat[3], &pat[4], &pat[5], &pat[6],
1579 &pat[7], &pat[8], &pat[9], &pat[10], &pat[11], &pat[12],
1580 &pat[13], &pat[14], &pat[15]);
1583 for (kk = 0; kk <= maxpayload - (TIMEVAL_LEN + ii); kk += ii)
1584 for (jj = 0; jj < ii; ++jj)
1585 bp[jj + kk] = pat[jj];
1586 if (!(options & F_QUIET)) {
1587 (void)printf("PATTERN: 0x");
1588 for (jj = 0; jj < ii; ++jj)
1589 (void)printf("%02x", bp[jj] & 0xFF);
1594 #if defined(IPSEC) && defined(IPSEC_POLICY_IPSEC)
1595 #define SECOPT " [-P policy]"
1603 (void)fprintf(stderr, "%s\n%s\n%s\n%s\n%s\n%s\n",
1604 "usage: ping [-AaDdfnoQqRrv] [-c count] [-i wait] [-l preload] [-M mask | time]",
1605 " [-m ttl]" SECOPT " [-p pattern] [-S src_addr] [-s packetsize]",
1606 " [-t timeout] [-z tos] host",
1607 " ping [-AaDdfLnoQqRrv] [-c count] [-I iface] [-i wait] [-l preload]",
1608 " [-M mask | time] [-m ttl]" SECOPT " [-p pattern] [-S src_addr]",
1609 " [-s packetsize] [-T ttl] [-t timeout] [-z tos] mcast-group");