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. All advertising materials mentioning features or use of this software
17 * must display the following acknowledgement:
18 * This product includes software developed by the University of
19 * California, Berkeley and its contributors.
20 * 4. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * @(#) Copyright (c) 1989, 1993 The Regents of the University of California. All rights reserved.
37 * @(#)ping.c 8.1 (Berkeley) 6/5/93
38 * $FreeBSD: src/sbin/ping/ping.c,v 1.52.2.13 2002/10/29 10:23:21 maxim Exp $
39 * $DragonFly: src/sbin/ping/ping.c,v 1.3 2003/09/28 14:39:20 hmp Exp $
45 * Using the Internet Control Message Protocol (ICMP) "ECHO" facility,
46 * measure round-trip-delays and packet loss across network paths.
50 * U. S. Army Ballistic Research Laboratory
54 * Public Domain. Distribution Unlimited.
56 * More statistics could always be gathered.
57 * This program has to run SUID to ROOT to access the ICMP socket.
60 #include <sys/param.h> /* NB: we rely on this for <sys/types.h> */
75 #include <sys/socket.h>
79 #include <netinet/in.h>
80 #include <netinet/in_systm.h>
81 #include <netinet/ip.h>
82 #include <netinet/ip_icmp.h>
83 #include <netinet/ip_var.h>
84 #include <arpa/inet.h>
87 #include <netinet6/ipsec.h>
90 #define INADDR_LEN ((int)sizeof(in_addr_t))
91 #define PHDR_LEN ((int)sizeof(struct timeval))
92 #define DEFDATALEN (64 - PHDR_LEN) /* default data length */
93 #define FLOOD_BACKOFF 20000 /* usecs to back off if F_FLOOD mode */
94 /* runs out of buffer space */
95 #define MAXIPLEN (sizeof(struct ip) + MAX_IPOPTLEN)
96 #define MAXICMPLEN (ICMP_ADVLENMIN + MAX_IPOPTLEN)
97 #define MINICMPLEN ICMP_MINLEN
98 #define MAXPAYLOAD (IP_MAXPACKET - MAXIPLEN - MINICMPLEN)
99 #define MAXWAIT 10 /* max seconds to wait for response */
100 #define MAXALARM (60 * 60) /* max seconds for alarm timeout */
102 #define A(bit) rcvd_tbl[(bit)>>3] /* identify byte in array */
103 #define B(bit) (1 << ((bit) & 0x07)) /* identify bit in byte */
104 #define SET(bit) (A(bit) |= B(bit))
105 #define CLR(bit) (A(bit) &= (~B(bit)))
106 #define TST(bit) (A(bit) & B(bit))
108 /* various options */
110 #define F_FLOOD 0x0001
111 #define F_INTERVAL 0x0002
112 #define F_NUMERIC 0x0004
113 #define F_PINGFILLED 0x0008
114 #define F_QUIET 0x0010
115 #define F_RROUTE 0x0020
116 #define F_SO_DEBUG 0x0040
117 #define F_SO_DONTROUTE 0x0080
118 #define F_VERBOSE 0x0100
119 #define F_QUIET2 0x0200
120 #define F_NOLOOP 0x0400
121 #define F_MTTL 0x0800
123 #define F_AUDIBLE 0x2000
125 #ifdef IPSEC_POLICY_IPSEC
126 #define F_POLICY 0x4000
127 #endif /*IPSEC_POLICY_IPSEC*/
130 #define F_MISSED 0x10000
133 * MAX_DUP_CHK is the number of bits in received table, i.e. the maximum
134 * number of received sequence numbers we can keep track of. Change 128
135 * to 8192 for complete accuracy...
137 #define MAX_DUP_CHK (8 * 128)
138 int mx_dup_ck = MAX_DUP_CHK;
139 char rcvd_tbl[MAX_DUP_CHK / 8];
141 struct sockaddr_in whereto; /* who to ping */
142 int datalen = DEFDATALEN;
143 int s; /* socket file descriptor */
144 u_char outpack[MINICMPLEN + MAXPAYLOAD];
145 char BSPACE = '\b'; /* characters written for flood */
146 char BBELL = '\a'; /* characters written for MISSED and AUDIBLE */
150 int ident; /* process id to identify our packets */
151 int uid; /* cached uid for micro-optimization */
154 long npackets; /* max packets to transmit */
155 long nreceived; /* # of packets we got back */
156 long nrepeats; /* number of duplicates */
157 long ntransmitted; /* sequence # for outbound packets = #sent */
158 long nmissedmax; /* max value of ntransmitted - nreceived - 1 */
159 int interval = 1000; /* interval between packets, ms */
162 int timing; /* flag to do timing */
163 double tmin = 999999999.0; /* minimum round trip time */
164 double tmax = 0.0; /* maximum round trip time */
165 double tsum = 0.0; /* sum of all times, for doing average */
166 double tsumsq = 0.0; /* sum of all times squared, for std. dev. */
168 volatile sig_atomic_t finish_up; /* nonzero if we've been told to finish up */
170 volatile sig_atomic_t siginfo_p;
172 static void fill(char *, char *);
173 static u_short in_cksum(u_short *, int);
174 static void check_status(void);
175 static void finish(void) __dead2;
176 static void pinger(void);
177 static char *pr_addr(struct in_addr);
178 static void pr_icmph(struct icmp *);
179 static void pr_iph(struct ip *);
180 static void pr_pack(char *, int, struct sockaddr_in *, struct timeval *);
181 static void pr_retip(struct ip *);
182 static void status(int);
183 static void stopit(int);
184 static void tvsub(struct timeval *, struct timeval *);
185 static void usage(void) __dead2;
188 main(int argc, char **argv)
190 struct in_addr ifaddr;
193 struct sigaction si_sa;
194 struct sockaddr_in from, sin;
196 struct timeval last, intvl;
198 struct sockaddr_in *to;
200 u_char *datap, packet[IP_MAXPACKET];
201 char *ep, *source, *target;
202 #ifdef IPSEC_POLICY_IPSEC
203 char *policy_in, *policy_out;
205 u_long alarmtimeout, ultmp;
206 int ch, hold, i, packlen, preload, sockerrno, almost_done = 0, ttl;
207 char ctrl[CMSG_SPACE(sizeof(struct timeval))];
208 char hnamebuf[MAXHOSTNAMELEN], snamebuf[MAXHOSTNAMELEN];
210 char rspace[MAX_IPOPTLEN]; /* record route space */
212 unsigned char mttl, loop;
215 #ifdef IPSEC_POLICY_IPSEC
216 policy_in = policy_out = NULL;
220 * Do the stuff that we need root priv's for *first*, and
221 * then drop our setuid bit. Save error reporting for
224 s = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
230 alarmtimeout = preload = 0;
232 datap = &outpack[MINICMPLEN + PHDR_LEN];
233 while ((ch = getopt(argc, argv,
234 "AI:LQRS:T:c:adfi:l:m:np:qrs:t:v"
236 #ifdef IPSEC_POLICY_IPSEC
238 #endif /*IPSEC_POLICY_IPSEC*/
247 options |= F_AUDIBLE;
250 ultmp = strtoul(optarg, &ep, 0);
251 if (*ep || ep == optarg || ultmp > LONG_MAX || !ultmp)
253 "invalid count of packets to transmit: `%s'",
258 options |= F_SO_DEBUG;
263 err(EX_NOPERM, "-f flag");
266 setbuf(stdout, (char *)NULL);
268 case 'i': /* wait between sending packets */
269 t = strtod(optarg, &ep) * 1000.0;
270 if (*ep || ep == optarg || t > (double)INT_MAX)
271 errx(EX_USAGE, "invalid timing interval: `%s'",
273 options |= F_INTERVAL;
275 if (uid && interval < 1000) {
277 err(EX_NOPERM, "-i interval too short");
280 case 'I': /* multicast interface */
281 if (inet_aton(optarg, &ifaddr) == 0)
283 "invalid multicast interface: `%s'",
288 ultmp = strtoul(optarg, &ep, 0);
289 if (*ep || ep == optarg || ultmp > INT_MAX)
291 "invalid preload value: `%s'", optarg);
294 err(EX_NOPERM, "-l flag");
303 ultmp = strtoul(optarg, &ep, 0);
304 if (*ep || ep == optarg || ultmp > 255)
305 errx(EX_USAGE, "invalid TTL: `%s'", optarg);
310 options |= F_NUMERIC;
312 case 'p': /* fill buffer with user pattern */
313 options |= F_PINGFILLED;
314 fill((char *)datap, optarg);
326 options |= F_SO_DONTROUTE;
328 case 's': /* size of packet to send */
331 err(EX_NOPERM, "-s flag");
333 ultmp = strtoul(optarg, &ep, 0);
334 if (ultmp > MAXPAYLOAD)
336 "packet size too large: %lu > %u",
338 if (*ep || ep == optarg)
339 errx(EX_USAGE, "invalid packet size: `%s'",
347 alarmtimeout = strtoul(optarg, &ep, 0);
348 if ((alarmtimeout < 1) || (alarmtimeout == ULONG_MAX))
349 errx(EX_USAGE, "invalid timeout: `%s'",
351 if (alarmtimeout > MAXALARM)
352 errx(EX_USAGE, "invalid timeout: `%s' > %d",
354 alarm((int)alarmtimeout);
356 case 'T': /* multicast TTL */
357 ultmp = strtoul(optarg, &ep, 0);
358 if (*ep || ep == optarg || ultmp > 255)
359 errx(EX_USAGE, "invalid multicast TTL: `%s'",
365 options |= F_VERBOSE;
368 #ifdef IPSEC_POLICY_IPSEC
371 if (!strncmp("in", optarg, 2))
372 policy_in = strdup(optarg);
373 else if (!strncmp("out", optarg, 3))
374 policy_out = strdup(optarg);
376 errx(1, "invalid security policy");
378 #endif /*IPSEC_POLICY_IPSEC*/
385 if (argc - optind != 1)
387 target = argv[optind];
390 bzero((char *)&sin, sizeof(sin));
391 sin.sin_family = AF_INET;
392 if (inet_aton(source, &sin.sin_addr) != 0) {
395 hp = gethostbyname2(source, AF_INET);
397 errx(EX_NOHOST, "cannot resolve %s: %s",
398 source, hstrerror(h_errno));
400 sin.sin_len = sizeof sin;
401 if (hp->h_length > sizeof(sin.sin_addr) ||
403 errx(1, "gethostbyname2: illegal address");
404 memcpy(&sin.sin_addr, hp->h_addr_list[0],
405 sizeof(sin.sin_addr));
406 (void)strncpy(snamebuf, hp->h_name,
407 sizeof(snamebuf) - 1);
408 snamebuf[sizeof(snamebuf) - 1] = '\0';
409 shostname = snamebuf;
411 if (bind(s, (struct sockaddr *)&sin, sizeof sin) == -1)
415 bzero(&whereto, sizeof(whereto));
417 to->sin_family = AF_INET;
418 to->sin_len = sizeof *to;
419 if (inet_aton(target, &to->sin_addr) != 0) {
422 hp = gethostbyname2(target, AF_INET);
424 errx(EX_NOHOST, "cannot resolve %s: %s",
425 target, hstrerror(h_errno));
427 if (hp->h_length > sizeof(to->sin_addr))
428 errx(1, "gethostbyname2 returned an illegal address");
429 memcpy(&to->sin_addr, hp->h_addr_list[0], sizeof to->sin_addr);
430 (void)strncpy(hnamebuf, hp->h_name, sizeof(hnamebuf) - 1);
431 hnamebuf[sizeof(hnamebuf) - 1] = '\0';
435 if (options & F_FLOOD && options & F_INTERVAL)
436 errx(EX_USAGE, "-f and -i: incompatible options");
438 if (options & F_FLOOD && IN_MULTICAST(ntohl(to->sin_addr.s_addr)))
440 "-f flag cannot be used with multicast destination");
441 if (options & (F_MIF | F_NOLOOP | F_MTTL)
442 && !IN_MULTICAST(ntohl(to->sin_addr.s_addr)))
444 "-I, -L, -T flags cannot be used with unicast destination");
446 if (datalen >= PHDR_LEN) /* can we time transfer */
448 packlen = MAXIPLEN + MAXICMPLEN + datalen;
449 packlen = packlen > IP_MAXPACKET ? IP_MAXPACKET : packlen;
451 if (!(options & F_PINGFILLED))
452 for (i = PHDR_LEN; i < datalen; ++i)
455 ident = getpid() & 0xFFFF;
459 err(EX_OSERR, "socket");
462 if (options & F_SO_DEBUG)
463 (void)setsockopt(s, SOL_SOCKET, SO_DEBUG, (char *)&hold,
465 if (options & F_SO_DONTROUTE)
466 (void)setsockopt(s, SOL_SOCKET, SO_DONTROUTE, (char *)&hold,
469 #ifdef IPSEC_POLICY_IPSEC
470 if (options & F_POLICY) {
472 if (policy_in != NULL) {
473 buf = ipsec_set_policy(policy_in, strlen(policy_in));
475 errx(EX_CONFIG, "%s", ipsec_strerror());
476 if (setsockopt(s, IPPROTO_IP, IP_IPSEC_POLICY,
477 buf, ipsec_get_policylen(buf)) < 0)
479 "ipsec policy cannot be configured");
483 if (policy_out != NULL) {
484 buf = ipsec_set_policy(policy_out, strlen(policy_out));
486 errx(EX_CONFIG, "%s", ipsec_strerror());
487 if (setsockopt(s, IPPROTO_IP, IP_IPSEC_POLICY,
488 buf, ipsec_get_policylen(buf)) < 0)
490 "ipsec policy cannot be configured");
494 #endif /*IPSEC_POLICY_IPSEC*/
497 /* record route option */
498 if (options & F_RROUTE) {
500 bzero(rspace, sizeof(rspace));
501 rspace[IPOPT_OPTVAL] = IPOPT_RR;
502 rspace[IPOPT_OLEN] = sizeof(rspace) - 1;
503 rspace[IPOPT_OFFSET] = IPOPT_MINOFF;
504 rspace[sizeof(rspace) - 1] = IPOPT_EOL;
505 if (setsockopt(s, IPPROTO_IP, IP_OPTIONS, rspace,
507 err(EX_OSERR, "setsockopt IP_OPTIONS");
510 "record route not available in this implementation");
511 #endif /* IP_OPTIONS */
514 if (options & F_TTL) {
515 if (setsockopt(s, IPPROTO_IP, IP_TTL, &ttl,
517 err(EX_OSERR, "setsockopt IP_TTL");
520 if (options & F_NOLOOP) {
521 if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_LOOP, &loop,
523 err(EX_OSERR, "setsockopt IP_MULTICAST_LOOP");
526 if (options & F_MTTL) {
527 if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL, &mttl,
529 err(EX_OSERR, "setsockopt IP_MULTICAST_TTL");
532 if (options & F_MIF) {
533 if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_IF, &ifaddr,
534 sizeof(ifaddr)) < 0) {
535 err(EX_OSERR, "setsockopt IP_MULTICAST_IF");
540 if (setsockopt(s, SOL_SOCKET, SO_TIMESTAMP, &on, sizeof(on)) < 0)
541 err(EX_OSERR, "setsockopt SO_TIMESTAMP");
546 * When pinging the broadcast address, you can get a lot of answers.
547 * Doing something so evil is useful if you are trying to stress the
548 * ethernet, or just want to fill the arp cache to get some stuff for
549 * /etc/ethers. But beware: RFC 1122 allows hosts to ignore broadcast
550 * or multicast pings if they wish.
554 * XXX receive buffer needs undetermined space for mbuf overhead
557 hold = IP_MAXPACKET + 128;
558 (void)setsockopt(s, SOL_SOCKET, SO_RCVBUF, (char *)&hold,
562 (void)setsockopt(s, SOL_SOCKET, SO_SNDBUF, (char *)&hold,
566 if (to->sin_family == AF_INET) {
567 (void)printf("PING %s (%s)", hostname,
568 inet_ntoa(to->sin_addr));
570 (void)printf(" from %s", shostname);
571 (void)printf(": %d data bytes\n", datalen);
573 (void)printf("PING %s: %d data bytes\n", hostname, datalen);
576 * Use sigaction() instead of signal() to get unambiguous semantics,
577 * in particular with SA_RESTART not set.
580 sigemptyset(&si_sa.sa_mask);
583 si_sa.sa_handler = stopit;
584 if (sigaction(SIGINT, &si_sa, 0) == -1) {
585 err(EX_OSERR, "sigaction SIGINT");
588 si_sa.sa_handler = status;
589 if (sigaction(SIGINFO, &si_sa, 0) == -1) {
590 err(EX_OSERR, "sigaction");
593 if (alarmtimeout > 0) {
594 si_sa.sa_handler = stopit;
595 if (sigaction(SIGALRM, &si_sa, 0) == -1)
596 err(EX_OSERR, "sigaction SIGALRM");
599 bzero(&msg, sizeof(msg));
600 msg.msg_name = (caddr_t)&from;
604 msg.msg_control = (caddr_t)ctrl;
606 iov.iov_base = packet;
607 iov.iov_len = packlen;
609 if (tcgetattr(STDOUT_FILENO, &ts) != -1) {
610 reset_kerninfo = !(ts.c_lflag & NOKERNINFO);
611 ts.c_lflag |= NOKERNINFO;
612 tcsetattr(STDOUT_FILENO, TCSANOW, &ts);
616 pinger(); /* send the first ping */
618 if (npackets != 0 && preload > npackets)
620 while (preload--) /* fire off them quickies */
623 (void)gettimeofday(&last, NULL);
625 if (options & F_FLOOD) {
627 intvl.tv_usec = 10000;
629 intvl.tv_sec = interval / 1000;
630 intvl.tv_usec = interval % 1000 * 1000;
636 struct timeval timeout, now;
641 errx(EX_OSERR, "descriptor too large");
644 (void)gettimeofday(&now, NULL);
645 timeout.tv_sec = last.tv_sec + intvl.tv_sec - now.tv_sec;
646 timeout.tv_usec = last.tv_usec + intvl.tv_usec - now.tv_usec;
647 while (timeout.tv_usec < 0) {
648 timeout.tv_usec += 1000000;
651 while (timeout.tv_usec >= 1000000) {
652 timeout.tv_usec -= 1000000;
655 if (timeout.tv_sec < 0)
656 timeout.tv_sec = timeout.tv_usec = 0;
657 n = select(s + 1, &rfds, NULL, NULL, &timeout);
659 continue; /* Must be EINTR. */
661 struct timeval *t = 0;
663 struct cmsghdr *cmsg = (struct cmsghdr *)&ctrl;
665 msg.msg_controllen = sizeof(ctrl);
667 msg.msg_namelen = sizeof(from);
668 if ((cc = recvmsg(s, &msg, 0)) < 0) {
675 if (cmsg->cmsg_level == SOL_SOCKET &&
676 cmsg->cmsg_type == SCM_TIMESTAMP &&
677 cmsg->cmsg_len == CMSG_LEN(sizeof *t)) {
678 /* Copy to avoid alignment problems: */
679 memcpy(&now,CMSG_DATA(cmsg),sizeof(now));
684 (void)gettimeofday(&now, NULL);
687 pr_pack((char *)packet, cc, &from, t);
688 if (npackets && nreceived >= npackets)
691 if (n == 0 || options & F_FLOOD) {
692 if (!npackets || ntransmitted < npackets)
700 intvl.tv_sec = 2 * tmax / 1000;
704 intvl.tv_sec = MAXWAIT;
706 (void)gettimeofday(&last, NULL);
708 if (ntransmitted - nreceived - 1 > nmissedmax) {
709 nmissedmax = ntransmitted - nreceived - 1;
710 if (options & F_MISSED)
711 (void)write(STDOUT_FILENO, &BBELL, 1);
717 exit(0); /* Make the compiler happy */
722 * Set the global bit that causes the main loop to quit.
723 * Do NOT call finish() from here, since finish() does far too much
724 * to be called from a signal handler.
727 stopit(int sig __unused)
735 * Compose and transmit an ICMP ECHO REQUEST packet. The IP packet
736 * will be added on by the kernel. The ID field is our UNIX process ID,
737 * and the sequence number is an ascending integer. The first PHDR_LEN
738 * bytes of the data portion are used to hold a UNIX "timeval" struct in
739 * host byte-order, to compute the round-trip time.
747 icp = (struct icmp *)outpack;
748 icp->icmp_type = ICMP_ECHO;
751 icp->icmp_seq = ntransmitted;
752 icp->icmp_id = ident; /* ID */
754 CLR(icp->icmp_seq % mx_dup_ck);
757 (void)gettimeofday((struct timeval *)&outpack[MINICMPLEN],
758 (struct timezone *)NULL);
760 cc = MINICMPLEN + datalen;
762 /* compute ICMP checksum here */
763 icp->icmp_cksum = in_cksum((u_short *)icp, cc);
765 i = sendto(s, (char *)outpack, cc, 0, (struct sockaddr *)&whereto,
768 if (i < 0 || i != cc) {
770 if (options & F_FLOOD && errno == ENOBUFS) {
771 usleep(FLOOD_BACKOFF);
776 warn("%s: partial write: %d of %d bytes",
781 if (!(options & F_QUIET) && options & F_FLOOD)
782 (void)write(STDOUT_FILENO, &DOT, 1);
787 * Print out the packet, if it came from us. This logic is necessary
788 * because ALL readers of the ICMP socket get a copy of ALL ICMP packets
789 * which arrive ('tis only fair). This permits multiple copies of this
790 * program to be run without having intermingled output (or statistics!).
793 pr_pack(char *buf, int cc, struct sockaddr_in *from, struct timeval *tv)
801 int dupflag, hlen, i, j;
802 static int old_rrlen;
803 static char old_rr[MAX_IPOPTLEN];
805 /* Check the IP header */
806 ip = (struct ip *)buf;
807 hlen = ip->ip_hl << 2;
808 if (cc < hlen + ICMP_MINLEN) {
809 if (options & F_VERBOSE)
810 warn("packet too short (%d bytes) from %s", cc,
811 inet_ntoa(from->sin_addr));
815 /* Now the ICMP part */
817 icp = (struct icmp *)(buf + hlen);
818 if (icp->icmp_type == ICMP_ECHOREPLY) {
819 if (icp->icmp_id != ident)
820 return; /* 'Twas not our ECHO */
826 tp = (struct timeval *)&icp->icmp_ip;
828 tp = (struct timeval *)icp->icmp_data;
830 /* Avoid unaligned data: */
831 memcpy(&tv1,tp,sizeof(tv1));
833 triptime = ((double)tv->tv_sec) * 1000.0 +
834 ((double)tv->tv_usec) / 1000.0;
836 tsumsq += triptime * triptime;
843 if (TST(icp->icmp_seq % mx_dup_ck)) {
848 SET(icp->icmp_seq % mx_dup_ck);
852 if (options & F_QUIET)
855 if (options & F_FLOOD)
856 (void)write(STDOUT_FILENO, &BSPACE, 1);
858 (void)printf("%d bytes from %s: icmp_seq=%u", cc,
859 inet_ntoa(*(struct in_addr *)&from->sin_addr.s_addr),
861 (void)printf(" ttl=%d", ip->ip_ttl);
863 (void)printf(" time=%.3f ms", triptime);
865 (void)printf(" (DUP!)");
866 if (options & F_AUDIBLE)
867 (void)write(STDOUT_FILENO, &BBELL, 1);
869 cp = (u_char*)&icp->icmp_data[PHDR_LEN];
870 dp = &outpack[MINICMPLEN + PHDR_LEN];
871 for (i = PHDR_LEN; i < datalen; ++i, ++cp, ++dp) {
873 (void)printf("\nwrong data byte #%d should be 0x%x but was 0x%x",
875 (void)printf("\ncp:");
876 cp = (u_char*)&icp->icmp_data[0];
877 for (i = 0; i < datalen; ++i, ++cp) {
879 (void)printf("\n\t");
880 (void)printf("%x ", *cp);
882 (void)printf("\ndp:");
883 cp = &outpack[MINICMPLEN];
884 for (i = 0; i < datalen; ++i, ++cp) {
886 (void)printf("\n\t");
887 (void)printf("%x ", *cp);
895 * We've got something other than an ECHOREPLY.
896 * See if it's a reply to something that we sent.
897 * We can compare IP destination, protocol,
898 * and ICMP type and ID.
900 * Only print all the error messages if we are running
901 * as root to avoid leaking information not normally
902 * available to those not running as root.
905 struct ip *oip = &icp->icmp_ip;
907 struct ip *oip = (struct ip *)icp->icmp_data;
909 struct icmp *oicmp = (struct icmp *)(oip + 1);
911 if (((options & F_VERBOSE) && uid == 0) ||
912 (!(options & F_QUIET2) &&
913 (oip->ip_dst.s_addr == whereto.sin_addr.s_addr) &&
914 (oip->ip_p == IPPROTO_ICMP) &&
915 (oicmp->icmp_type == ICMP_ECHO) &&
916 (oicmp->icmp_id == ident))) {
917 (void)printf("%d bytes from %s: ", cc,
918 pr_addr(from->sin_addr));
924 /* Display any IP options */
925 cp = (u_char *)buf + sizeof(struct ip);
927 for (; hlen > (int)sizeof(struct ip); --hlen, ++cp)
933 (void)printf("\nLSRR: ");
934 j = cp[IPOPT_OLEN] - IPOPT_MINOFF + 1;
937 if (j >= INADDR_LEN &&
938 j <= hlen - (int)sizeof(struct ip)) {
940 bcopy(++cp, &ina.s_addr, INADDR_LEN);
942 (void)printf("\t0.0.0.0");
947 cp += INADDR_LEN - 1;
954 (void)printf("\t(truncated route)\n");
957 j = cp[IPOPT_OLEN]; /* get length */
958 i = cp[IPOPT_OFFSET]; /* and pointer */
963 i = i - IPOPT_MINOFF + 1;
964 if (i < 0 || i > (hlen - (int)sizeof(struct ip))) {
969 && !bcmp((char *)cp, old_rr, i)
970 && !(options & F_FLOOD)) {
971 (void)printf("\t(same route)");
977 bcopy((char *)cp, old_rr, i);
979 (void)printf("\nRR: ");
981 if (i >= INADDR_LEN &&
982 i <= hlen - (int)sizeof(struct ip)) {
984 bcopy(++cp, &ina.s_addr, INADDR_LEN);
986 (void)printf("\t0.0.0.0");
991 cp += INADDR_LEN - 1;
998 (void)printf("\t(truncated route)");
1001 (void)printf("\nNOP");
1004 (void)printf("\nunknown option %x", *cp);
1007 if (!(options & F_FLOOD)) {
1008 (void)putchar('\n');
1009 (void)fflush(stdout);
1015 * Checksum routine for Internet Protocol family headers (C Version)
1018 in_cksum(u_short *addr, int len)
1033 * Our algorithm is simple, using a 32 bit accumulator (sum), we add
1034 * sequential 16 bit words to it, and at the end, fold back all the
1035 * carry bits from the top 16 bits into the lower 16 bits.
1042 /* mop up an odd byte, if necessary */
1044 last.uc[0] = *(u_char *)w;
1049 /* add back carry outs from top 16 bits to low 16 bits */
1050 sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */
1051 sum += (sum >> 16); /* add carry */
1052 answer = ~sum; /* truncate to 16 bits */
1058 * Subtract 2 timeval structs: out = out - in. Out is assumed to
1062 tvsub(struct timeval *out, struct timeval *in)
1065 if ((out->tv_usec -= in->tv_usec) < 0) {
1067 out->tv_usec += 1000000;
1069 out->tv_sec -= in->tv_sec;
1074 * Print out statistics when SIGINFO is received.
1078 status(int sig __unused)
1090 (void)fprintf(stderr,
1091 "\r%ld/%ld packets received (%.0f%%) %.3f min / %.3f avg / %.3f max\n",
1092 nreceived, ntransmitted,
1093 ntransmitted ? nreceived * 100.0 / ntransmitted : 0.0,
1094 nreceived ? tmin : 0.0,
1095 nreceived + nrepeats ? tsum / (nreceived + nrepeats) : tsum,
1102 * Print out statistics, and give up.
1110 (void)signal(SIGINT, SIG_IGN);
1111 (void)signal(SIGALRM, SIG_IGN);
1112 (void)putchar('\n');
1113 (void)fflush(stdout);
1114 (void)printf("--- %s ping statistics ---\n", hostname);
1115 (void)printf("%ld packets transmitted, ", ntransmitted);
1116 (void)printf("%ld packets received, ", nreceived);
1118 (void)printf("+%ld duplicates, ", nrepeats);
1120 if (nreceived > ntransmitted)
1121 (void)printf("-- somebody's printing up packets!");
1123 (void)printf("%d%% packet loss",
1124 (int)(((ntransmitted - nreceived) * 100) /
1127 (void)putchar('\n');
1128 if (nreceived && timing) {
1129 double n = nreceived + nrepeats;
1130 double avg = tsum / n;
1131 double vari = tsumsq / n - avg * avg;
1133 "round-trip min/avg/max/stddev = %.3f/%.3f/%.3f/%.3f ms\n",
1134 tmin, avg, tmax, sqrt(vari));
1136 if (reset_kerninfo && tcgetattr(STDOUT_FILENO, &ts) != -1) {
1137 ts.c_lflag &= ~NOKERNINFO;
1138 tcsetattr(STDOUT_FILENO, TCSANOW, &ts);
1148 static char *ttab[] = {
1149 "Echo Reply", /* ip + seq + udata */
1150 "Dest Unreachable", /* net, host, proto, port, frag, sr + IP */
1151 "Source Quench", /* IP */
1152 "Redirect", /* redirect type, gateway, + IP */
1154 "Time Exceeded", /* transit, frag reassem + IP */
1155 "Parameter Problem", /* pointer + IP */
1156 "Timestamp", /* id + seq + three timestamps */
1157 "Timestamp Reply", /* " */
1158 "Info Request", /* id + sq */
1159 "Info Reply" /* " */
1165 * Print a descriptive string about an ICMP header.
1168 pr_icmph(struct icmp *icp)
1171 switch(icp->icmp_type) {
1172 case ICMP_ECHOREPLY:
1173 (void)printf("Echo Reply\n");
1174 /* XXX ID + Seq + Data */
1177 switch(icp->icmp_code) {
1178 case ICMP_UNREACH_NET:
1179 (void)printf("Destination Net Unreachable\n");
1181 case ICMP_UNREACH_HOST:
1182 (void)printf("Destination Host Unreachable\n");
1184 case ICMP_UNREACH_PROTOCOL:
1185 (void)printf("Destination Protocol Unreachable\n");
1187 case ICMP_UNREACH_PORT:
1188 (void)printf("Destination Port Unreachable\n");
1190 case ICMP_UNREACH_NEEDFRAG:
1191 (void)printf("frag needed and DF set (MTU %d)\n",
1192 ntohs(icp->icmp_nextmtu));
1194 case ICMP_UNREACH_SRCFAIL:
1195 (void)printf("Source Route Failed\n");
1197 case ICMP_UNREACH_FILTER_PROHIB:
1198 (void)printf("Communication prohibited by filter\n");
1201 (void)printf("Dest Unreachable, Bad Code: %d\n",
1205 /* Print returned IP header information */
1207 pr_retip(&icp->icmp_ip);
1209 pr_retip((struct ip *)icp->icmp_data);
1212 case ICMP_SOURCEQUENCH:
1213 (void)printf("Source Quench\n");
1215 pr_retip(&icp->icmp_ip);
1217 pr_retip((struct ip *)icp->icmp_data);
1221 switch(icp->icmp_code) {
1222 case ICMP_REDIRECT_NET:
1223 (void)printf("Redirect Network");
1225 case ICMP_REDIRECT_HOST:
1226 (void)printf("Redirect Host");
1228 case ICMP_REDIRECT_TOSNET:
1229 (void)printf("Redirect Type of Service and Network");
1231 case ICMP_REDIRECT_TOSHOST:
1232 (void)printf("Redirect Type of Service and Host");
1235 (void)printf("Redirect, Bad Code: %d", icp->icmp_code);
1238 (void)printf("(New addr: %s)\n", inet_ntoa(icp->icmp_gwaddr));
1240 pr_retip(&icp->icmp_ip);
1242 pr_retip((struct ip *)icp->icmp_data);
1246 (void)printf("Echo Request\n");
1247 /* XXX ID + Seq + Data */
1250 switch(icp->icmp_code) {
1251 case ICMP_TIMXCEED_INTRANS:
1252 (void)printf("Time to live exceeded\n");
1254 case ICMP_TIMXCEED_REASS:
1255 (void)printf("Frag reassembly time exceeded\n");
1258 (void)printf("Time exceeded, Bad Code: %d\n",
1263 pr_retip(&icp->icmp_ip);
1265 pr_retip((struct ip *)icp->icmp_data);
1268 case ICMP_PARAMPROB:
1269 (void)printf("Parameter problem: pointer = 0x%02x\n",
1270 icp->icmp_hun.ih_pptr);
1272 pr_retip(&icp->icmp_ip);
1274 pr_retip((struct ip *)icp->icmp_data);
1278 (void)printf("Timestamp\n");
1279 /* XXX ID + Seq + 3 timestamps */
1281 case ICMP_TSTAMPREPLY:
1282 (void)printf("Timestamp Reply\n");
1283 /* XXX ID + Seq + 3 timestamps */
1286 (void)printf("Information Request\n");
1289 case ICMP_IREQREPLY:
1290 (void)printf("Information Reply\n");
1294 (void)printf("Address Mask Request\n");
1296 case ICMP_MASKREPLY:
1297 (void)printf("Address Mask Reply\n");
1299 case ICMP_ROUTERADVERT:
1300 (void)printf("Router Advertisement\n");
1302 case ICMP_ROUTERSOLICIT:
1303 (void)printf("Router Solicitation\n");
1306 (void)printf("Bad ICMP type: %d\n", icp->icmp_type);
1312 * Print an IP header with options.
1315 pr_iph(struct ip *ip)
1320 hlen = ip->ip_hl << 2;
1321 cp = (u_char *)ip + 20; /* point to options */
1323 (void)printf("Vr HL TOS Len ID Flg off TTL Pro cks Src Dst\n");
1324 (void)printf(" %1x %1x %02x %04x %04x",
1325 ip->ip_v, ip->ip_hl, ip->ip_tos, ntohs(ip->ip_len),
1327 (void)printf(" %1lx %04lx",
1328 (u_long) (ntohl(ip->ip_off) & 0xe000) >> 13,
1329 (u_long) ntohl(ip->ip_off) & 0x1fff);
1330 (void)printf(" %02x %02x %04x", ip->ip_ttl, ip->ip_p,
1332 (void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_src.s_addr));
1333 (void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_dst.s_addr));
1334 /* dump any option bytes */
1335 while (hlen-- > 20) {
1336 (void)printf("%02x", *cp++);
1338 (void)putchar('\n');
1343 * Return an ascii host address as a dotted quad and optionally with
1347 pr_addr(struct in_addr ina)
1350 static char buf[16 + 3 + MAXHOSTNAMELEN];
1352 if ((options & F_NUMERIC) ||
1353 !(hp = gethostbyaddr((char *)&ina, 4, AF_INET)))
1354 return inet_ntoa(ina);
1356 (void)snprintf(buf, sizeof(buf), "%s (%s)", hp->h_name,
1363 * Dump some info on a returned (via ICMP) IP packet.
1366 pr_retip(struct ip *ip)
1372 hlen = ip->ip_hl << 2;
1373 cp = (u_char *)ip + hlen;
1376 (void)printf("TCP: from port %u, to port %u (decimal)\n",
1377 (*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3)));
1378 else if (ip->ip_p == 17)
1379 (void)printf("UDP: from port %u, to port %u (decimal)\n",
1380 (*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3)));
1384 fill(char *bp, char *patp)
1390 for (cp = patp; *cp; cp++) {
1393 "patterns must be specified as hex digits");
1397 "%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x",
1398 &pat[0], &pat[1], &pat[2], &pat[3], &pat[4], &pat[5], &pat[6],
1399 &pat[7], &pat[8], &pat[9], &pat[10], &pat[11], &pat[12],
1400 &pat[13], &pat[14], &pat[15]);
1403 for (kk = 0; kk <= MAXPAYLOAD - (PHDR_LEN + ii); kk += ii)
1404 for (jj = 0; jj < ii; ++jj)
1405 bp[jj + kk] = pat[jj];
1406 if (!(options & F_QUIET)) {
1407 (void)printf("PATTERN: 0x");
1408 for (jj = 0; jj < ii; ++jj)
1409 (void)printf("%02x", bp[jj] & 0xFF);
1417 (void)fprintf(stderr, "%s\n%s\n%s\n",
1418 "usage: ping [-AQRadfnqrv] [-c count] [-i wait] [-l preload] [-m ttl]",
1421 #ifdef IPSEC_POLICY_IPSEC
1425 "[-s packetsize] [-S src_addr] [-t timeout]",
1426 " [host | [-L] [-I iface] [-T ttl] mcast-group]");