xref: /freebsd/sbin/ping/ping.c (revision 0de89efe5c443f213c7ea28773ef2dc6cf3af2ed)
1 /*
2  * Copyright (c) 1989, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Mike Muuss.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
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.
23  *
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
34  * SUCH DAMAGE.
35  */
36 
37 #ifndef lint
38 static const char copyright[] =
39 "@(#) Copyright (c) 1989, 1993\n\
40 	The Regents of the University of California.  All rights reserved.\n";
41 #endif /* not lint */
42 
43 #ifndef lint
44 /*
45 static char sccsid[] = "@(#)ping.c	8.1 (Berkeley) 6/5/93";
46 */
47 static const char rcsid[] =
48 	"$Id: ping.c,v 1.27 1997/08/07 02:41:15 julian Exp $";
49 #endif /* not lint */
50 
51 /*
52  *			P I N G . C
53  *
54  * Using the InterNet Control Message Protocol (ICMP) "ECHO" facility,
55  * measure round-trip-delays and packet loss across network paths.
56  *
57  * Author -
58  *	Mike Muuss
59  *	U. S. Army Ballistic Research Laboratory
60  *	December, 1983
61  *
62  * Status -
63  *	Public Domain.  Distribution Unlimited.
64  * Bugs -
65  *	More statistics could always be gathered.
66  *	This program has to run SUID to ROOT to access the ICMP socket.
67  */
68 
69 #include <sys/param.h>		/* NB: we rely on this for <sys/types.h> */
70 
71 #include <ctype.h>
72 #include <err.h>
73 #include <errno.h>
74 #include <math.h>
75 #include <netdb.h>
76 #include <signal.h>
77 #include <stdio.h>
78 #include <stdlib.h>
79 #include <string.h>
80 #include <sysexits.h>
81 #include <termios.h>
82 #include <unistd.h>
83 
84 #include <sys/socket.h>
85 #include <sys/file.h>
86 #include <sys/time.h>
87 
88 #include <netinet/in.h>
89 #include <netinet/in_systm.h>
90 #include <netinet/ip.h>
91 #include <netinet/ip_icmp.h>
92 #include <netinet/ip_var.h>
93 #include <arpa/inet.h>
94 
95 #define	DEFDATALEN	(64 - 8)	/* default data length */
96 #define	FLOOD_BACKOFF	20000		/* usecs to back off if F_FLOOD mode */
97 					/* runs out of buffer space */
98 #define	MAXIPLEN	60
99 #define	MAXICMPLEN	76
100 #define	MAXPACKET	(65536 - 60 - 8)/* max packet size */
101 #define	MAXWAIT		10		/* max seconds to wait for response */
102 #define	NROUTES		9		/* number of record route slots */
103 
104 #define	A(bit)		rcvd_tbl[(bit)>>3]	/* identify byte in array */
105 #define	B(bit)		(1 << ((bit) & 0x07))	/* identify bit in byte */
106 #define	SET(bit)	(A(bit) |= B(bit))
107 #define	CLR(bit)	(A(bit) &= (~B(bit)))
108 #define	TST(bit)	(A(bit) & B(bit))
109 
110 /* various options */
111 int options;
112 #define	F_FLOOD		0x0001
113 #define	F_INTERVAL	0x0002
114 #define	F_NUMERIC	0x0004
115 #define	F_PINGFILLED	0x0008
116 #define	F_QUIET		0x0010
117 #define	F_RROUTE	0x0020
118 #define	F_SO_DEBUG	0x0040
119 #define	F_SO_DONTROUTE	0x0080
120 #define	F_VERBOSE	0x0100
121 #define	F_QUIET2	0x0200
122 #define	F_NOLOOP	0x0400
123 #define	F_MTTL		0x0800
124 #define	F_MIF		0x1000
125 #define	F_AUDIBLE	0x2000
126 
127 /*
128  * MAX_DUP_CHK is the number of bits in received table, i.e. the maximum
129  * number of received sequence numbers we can keep track of.  Change 128
130  * to 8192 for complete accuracy...
131  */
132 #define	MAX_DUP_CHK	(8 * 128)
133 int mx_dup_ck = MAX_DUP_CHK;
134 char rcvd_tbl[MAX_DUP_CHK / 8];
135 
136 struct sockaddr whereto;	/* who to ping */
137 int datalen = DEFDATALEN;
138 int s;				/* socket file descriptor */
139 u_char outpack[MAXPACKET];
140 char BSPACE = '\b';		/* characters written for flood */
141 char DOT = '.';
142 char *hostname;
143 int ident;			/* process id to identify our packets */
144 int uid;			/* cached uid for micro-optimization */
145 
146 /* counters */
147 long npackets;			/* max packets to transmit */
148 long nreceived;			/* # of packets we got back */
149 long nrepeats;			/* number of duplicates */
150 long ntransmitted;		/* sequence # for outbound packets = #sent */
151 int interval = 1;		/* interval between packets */
152 
153 /* timing */
154 int timing;			/* flag to do timing */
155 double tmin = 999999999.0;	/* minimum round trip time */
156 double tmax = 0.0;		/* maximum round trip time */
157 double tsum = 0.0;		/* sum of all times, for doing average */
158 double tsumsq = 0.0;		/* sum of all times squared, for std. dev. */
159 
160 volatile sig_atomic_t finish_up;  /* nonzero if we've been told to finish up */
161 int reset_kerninfo;
162 volatile sig_atomic_t siginfo_p;
163 
164 static void fill(char *, char *);
165 static u_short in_cksum(u_short *, int);
166 static void catcher(int sig);
167 static void check_status(void);
168 static void finish(void) __dead2;
169 static void pinger(void);
170 static char *pr_addr(struct in_addr);
171 static void pr_icmph(struct icmp *);
172 static void pr_iph(struct ip *);
173 static void pr_pack(char *, int, struct sockaddr_in *);
174 static void pr_retip(struct ip *);
175 static void status(int);
176 static void stopit(int);
177 static void tvsub(struct timeval *, struct timeval *);
178 static void usage(const char *) __dead2;
179 
180 int
181 main(argc, argv)
182 	int argc;
183 	char *const *argv;
184 {
185 	struct timeval timeout;
186 	struct hostent *hp;
187 	struct sockaddr_in *to;
188 	struct termios ts;
189 	register int i;
190 	int ch, fdmask, hold, packlen, preload, sockerrno;
191 	struct in_addr ifaddr;
192 	unsigned char ttl, loop;
193 	u_char *datap, *packet;
194 	char *target, hnamebuf[MAXHOSTNAMELEN];
195 	char *ep;
196 	u_long ultmp;
197 #ifdef IP_OPTIONS
198 	char rspace[3 + 4 * NROUTES + 1];	/* record route space */
199 #endif
200 	struct sigaction si_sa;
201 
202 	/*
203 	 * Do the stuff that we need root priv's for *first*, and
204 	 * then drop our setuid bit.  Save error reporting for
205 	 * after arg parsing.
206 	 */
207 	s = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
208 	sockerrno = errno;
209 
210 	setuid(getuid());
211 	uid = getuid();
212 
213 	preload = 0;
214 
215 	datap = &outpack[8 + sizeof(struct timeval)];
216 	while ((ch = getopt(argc, argv, "I:LQRT:c:adfi:l:np:qrs:v")) != -1) {
217 		switch(ch) {
218 		case 'a':
219 			options |= F_AUDIBLE;
220 			break;
221 		case 'c':
222 			ultmp = strtoul(optarg, &ep, 0);
223 			if (*ep || ep == optarg || ultmp > LONG_MAX || !ultmp)
224 				errx(EX_USAGE,
225 				    "invalid count of packets to transmit: `%s'",
226 				    optarg);
227 			npackets = ultmp;
228 			break;
229 		case 'd':
230 			options |= F_SO_DEBUG;
231 			break;
232 		case 'f':
233 			if (getuid()) {
234 				errno = EPERM;
235 				err(EX_NOPERM, "-f flag");
236 			}
237 			options |= F_FLOOD;
238 			setbuf(stdout, (char *)NULL);
239 			break;
240 		case 'i':		/* wait between sending packets */
241 			ultmp = strtoul(optarg, &ep, 0);
242 			if (*ep || ep == optarg || ultmp > INT_MAX)
243 				errx(EX_USAGE,
244 				     "invalid timing interval: `%s'", optarg);
245 			options |= F_INTERVAL;
246 			interval = ultmp;
247 			break;
248 		case 'I':		/* multicast interface */
249 			if (inet_aton(optarg, &ifaddr) == 0)
250 				errx(EX_USAGE,
251 				     "invalid multicast interface: `%s'",
252 				     optarg);
253 			options |= F_MIF;
254 			break;
255 		case 'l':
256 			ultmp = strtoul(optarg, &ep, 0);
257 			if (*ep || ep == optarg || ultmp > INT_MAX)
258 				errx(EX_USAGE,
259 				     "invalid preload value: `%s'", optarg);
260 			if (getuid()) {
261 				errno = EPERM;
262 				err(EX_NOPERM, "-l flag");
263 			}
264 			options |= F_FLOOD;
265 			preload = ultmp;
266 			break;
267 		case 'L':
268 			options |= F_NOLOOP;
269 			loop = 0;
270 			break;
271 		case 'n':
272 			options |= F_NUMERIC;
273 			break;
274 		case 'p':		/* fill buffer with user pattern */
275 			options |= F_PINGFILLED;
276 			fill((char *)datap, optarg);
277 				break;
278 		case 'Q':
279 			options |= F_QUIET2;
280 			break;
281 		case 'q':
282 			options |= F_QUIET;
283 			break;
284 		case 'R':
285 			options |= F_RROUTE;
286 			break;
287 		case 'r':
288 			options |= F_SO_DONTROUTE;
289 			break;
290 		case 's':		/* size of packet to send */
291 			ultmp = strtoul(optarg, &ep, 0);
292 			if (ultmp > MAXPACKET)
293 				errx(EX_USAGE, "packet size too large: %lu",
294 				     ultmp);
295 			if (*ep || ep == optarg || !ultmp)
296 				errx(EX_USAGE, "invalid packet size: `%s'",
297 				     optarg);
298 			datalen = ultmp;
299 			break;
300 		case 'T':		/* multicast TTL */
301 			ultmp = strtoul(optarg, &ep, 0);
302 			if (*ep || ep == optarg || ultmp > 255)
303 				errx(EX_USAGE, "invalid multicast TTL: `%s'",
304 				     optarg);
305 			ttl = ultmp;
306 			options |= F_MTTL;
307 			break;
308 		case 'v':
309 			options |= F_VERBOSE;
310 			break;
311 		default:
312 
313 			usage(argv[0]);
314 		}
315 	}
316 
317 	if (argc - optind != 1)
318 		usage(argv[0]);
319 	target = argv[optind];
320 
321 	bzero((char *)&whereto, sizeof(struct sockaddr));
322 	to = (struct sockaddr_in *)&whereto;
323 	to->sin_family = AF_INET;
324 	if (inet_aton(target, &to->sin_addr) != 0) {
325 		hostname = target;
326 	} else {
327 		hp = gethostbyname2(target, AF_INET);
328 		if (!hp)
329 			errx(EX_NOHOST, "cannot resolve %s: %s",
330 			     target, hstrerror(h_errno));
331 
332 		to->sin_len = sizeof *to;
333 		if (hp->h_length > sizeof(to->sin_addr))
334 			errx(1,"gethostbyname2 returned an illegal address");
335 		memcpy(&to->sin_addr, hp->h_addr_list[0], sizeof to->sin_addr);
336 		(void)strncpy(hnamebuf, hp->h_name, sizeof(hnamebuf) - 1);
337 		hnamebuf[(sizeof hnamebuf) - 1] = '\0';
338 		hostname = hnamebuf;
339 	}
340 
341 	if (options & F_FLOOD && options & F_INTERVAL)
342 		errx(EX_USAGE, "-f and -i: incompatible options");
343 
344 	if (options & F_FLOOD && IN_MULTICAST(ntohl(to->sin_addr.s_addr)))
345 		errx(EX_USAGE,
346 		     "-f flag cannot be used with multicast destination");
347 	if (options & (F_MIF | F_NOLOOP | F_MTTL)
348 	    && !IN_MULTICAST(ntohl(to->sin_addr.s_addr)))
349 		errx(EX_USAGE,
350 		     "-I, -L, -T flags cannot be used with unicast destination");
351 
352 	if (datalen >= sizeof(struct timeval))	/* can we time transfer */
353 		timing = 1;
354 	packlen = datalen + MAXIPLEN + MAXICMPLEN;
355 	if (!(packet = (u_char *)malloc((size_t)packlen)))
356 		err(EX_UNAVAILABLE, "malloc");
357 
358 	if (!(options & F_PINGFILLED))
359 		for (i = 8; i < datalen; ++i)
360 			*datap++ = i;
361 
362 	ident = getpid() & 0xFFFF;
363 
364 	if (s < 0) {
365 		errno = sockerrno;
366 		err(EX_OSERR, "socket");
367 	}
368 	hold = 1;
369 	if (options & F_SO_DEBUG)
370 		(void)setsockopt(s, SOL_SOCKET, SO_DEBUG, (char *)&hold,
371 		    sizeof(hold));
372 	if (options & F_SO_DONTROUTE)
373 		(void)setsockopt(s, SOL_SOCKET, SO_DONTROUTE, (char *)&hold,
374 		    sizeof(hold));
375 
376 	/* record route option */
377 	if (options & F_RROUTE) {
378 #ifdef IP_OPTIONS
379 		rspace[IPOPT_OPTVAL] = IPOPT_RR;
380 		rspace[IPOPT_OLEN] = sizeof(rspace)-1;
381 		rspace[IPOPT_OFFSET] = IPOPT_MINOFF;
382 		if (setsockopt(s, IPPROTO_IP, IP_OPTIONS, rspace,
383 		    sizeof(rspace)) < 0)
384 			err(EX_OSERR, "setsockopt IP_OPTIONS");
385 #else
386 		errx(EX_UNAVAILABLE,
387 		  "record route not available in this implementation");
388 #endif /* IP_OPTIONS */
389 	}
390 
391 	if (options & F_NOLOOP) {
392 		if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_LOOP, &loop,
393 		    sizeof(loop)) < 0) {
394 			err(EX_OSERR, "setsockopt IP_MULTICAST_LOOP");
395 		}
396 	}
397 	if (options & F_MTTL) {
398 		if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL, &ttl,
399 		    sizeof(ttl)) < 0) {
400 			err(EX_OSERR, "setsockopt IP_MULTICAST_TTL");
401 		}
402 	}
403 	if (options & F_MIF) {
404 		if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_IF, &ifaddr,
405 		    sizeof(ifaddr)) < 0) {
406 			err(EX_OSERR, "setsockopt IP_MULTICAST_IF");
407 		}
408 	}
409 
410 	/*
411 	 * When pinging the broadcast address, you can get a lot of answers.
412 	 * Doing something so evil is useful if you are trying to stress the
413 	 * ethernet, or just want to fill the arp cache to get some stuff for
414 	 * /etc/ethers.  But beware: RFC 1122 allows hosts to ignore broadcast
415 	 * or multicast pings if they wish.
416 	 */
417 	hold = 48 * 1024;
418 	(void)setsockopt(s, SOL_SOCKET, SO_RCVBUF, (char *)&hold,
419 	    sizeof(hold));
420 
421 	if (to->sin_family == AF_INET)
422 		(void)printf("PING %s (%s): %d data bytes\n", hostname,
423 		    inet_ntoa(to->sin_addr),
424 		    datalen);
425 	else
426 		(void)printf("PING %s: %d data bytes\n", hostname, datalen);
427 
428 	/*
429 	 * Use sigaction() instead of signal() to get unambiguous semantics,
430 	 * in particular with SA_RESTART not set.
431 	 */
432 
433 	sigemptyset(&si_sa.sa_mask);
434 	si_sa.sa_flags = 0;
435 
436 	si_sa.sa_handler = stopit;
437 	if (sigaction(SIGINT, &si_sa, 0) == -1) {
438 		err(EX_OSERR, "sigaction SIGINT");
439 	}
440 
441 	si_sa.sa_handler = catcher;
442 	if (sigaction(SIGALRM, &si_sa, 0) == -1) {
443 		err(EX_OSERR, "sigaction SIGALRM");
444 	}
445 
446 	si_sa.sa_handler = status;
447 	if (sigaction(SIGINFO, &si_sa, 0) == -1) {
448 		err(EX_OSERR, "sigaction");
449 	}
450 
451 	if (tcgetattr(STDOUT_FILENO, &ts) != -1) {
452 		reset_kerninfo = !(ts.c_lflag & NOKERNINFO);
453 		ts.c_lflag |= NOKERNINFO;
454 		tcsetattr(STDOUT_FILENO, TCSANOW, &ts);
455 	}
456 
457 	while (preload--)		/* fire off them quickies */
458 		pinger();
459 
460 	if ((options & F_FLOOD) == 0)
461 		catcher(0);		/* start things going */
462 
463 	while (!finish_up) {
464 		struct sockaddr_in from;
465 		register int cc;
466 		int fromlen;
467 
468 		check_status();
469 		if (options & F_FLOOD) {
470 			pinger();
471 			timeout.tv_sec = 0;
472 			timeout.tv_usec = 10000;
473 			fdmask = 1 << s;
474 			if (select(s + 1, (fd_set *)&fdmask, (fd_set *)NULL,
475 			    (fd_set *)NULL, &timeout) < 1)
476 				continue;
477 		}
478 		fromlen = sizeof(from);
479 		if ((cc = recvfrom(s, (char *)packet, packlen, 0,
480 		    (struct sockaddr *)&from, &fromlen)) < 0) {
481 			if (errno == EINTR)
482 				continue;
483 			perror("ping: recvfrom");
484 			continue;
485 		}
486 		pr_pack((char *)packet, cc, &from);
487 		if (npackets && nreceived >= npackets)
488 			break;
489 	}
490 	finish();
491 	/* NOTREACHED */
492 	exit(0);	/* Make the compiler happy */
493 }
494 
495 /*
496  * stopit --
497  *	Set the global bit that causes the main loop to quit.
498  * Do NOT call finish() from here, since finish() does far too much
499  * to be called from a signal handler.
500  */
501 void
502 stopit(sig)
503 	int sig;
504 {
505 	finish_up = 1;
506 }
507 
508 /*
509  * catcher --
510  *	This routine causes another PING to be transmitted, and then
511  * schedules another SIGALRM for 1 second from now.
512  *
513  * bug --
514  *	Our sense of time will slowly skew (i.e., packets will not be
515  * launched exactly at 1-second intervals).  This does not affect the
516  * quality of the delay and loss statistics.
517  */
518 static void
519 catcher(int sig)
520 {
521 	int waittime;
522 	struct sigaction si_sa;
523 
524 	pinger();
525 
526 	if (!npackets || ntransmitted < npackets)
527 		(void)alarm((u_int)interval);
528 	else {
529 		if (nreceived) {
530 			waittime = 2 * tmax / 1000;
531 			if (!waittime)
532 				waittime = 1;
533 		} else
534 			waittime = MAXWAIT;
535 
536 		si_sa.sa_handler = stopit;
537 		sigemptyset(&si_sa.sa_mask);
538 		si_sa.sa_flags = 0;
539 		if (sigaction(SIGALRM, &si_sa, 0) == -1) {
540 			finish_up = 1;
541 			return;
542 		}
543 		(void)alarm((u_int)waittime);
544 	}
545 }
546 
547 /*
548  * pinger --
549  *	Compose and transmit an ICMP ECHO REQUEST packet.  The IP packet
550  * will be added on by the kernel.  The ID field is our UNIX process ID,
551  * and the sequence number is an ascending integer.  The first 8 bytes
552  * of the data portion are used to hold a UNIX "timeval" struct in host
553  * byte-order, to compute the round-trip time.
554  *
555  * bug --
556  *	this does far too much to be called from a signal handler.
557  */
558 static void
559 pinger(void)
560 {
561 	register struct icmp *icp;
562 	register int cc;
563 	int i;
564 
565 	icp = (struct icmp *)outpack;
566 	icp->icmp_type = ICMP_ECHO;
567 	icp->icmp_code = 0;
568 	icp->icmp_cksum = 0;
569 	icp->icmp_seq = ntransmitted;
570 	icp->icmp_id = ident;			/* ID */
571 
572 	CLR(icp->icmp_seq % mx_dup_ck);
573 
574 	if (timing)
575 		(void)gettimeofday((struct timeval *)&outpack[8],
576 		    (struct timezone *)NULL);
577 
578 	cc = datalen + 8;			/* skips ICMP portion */
579 
580 	/* compute ICMP checksum here */
581 	icp->icmp_cksum = in_cksum((u_short *)icp, cc);
582 
583 	i = sendto(s, (char *)outpack, cc, 0, &whereto,
584 	    sizeof(struct sockaddr));
585 
586 	if (i < 0 || i != cc)  {
587 		if (i < 0) {
588 			if (options & F_FLOOD && errno == ENOBUFS) {
589 				usleep(FLOOD_BACKOFF);
590 				return;
591 			}
592 			warn("sendto");
593 		} else {
594 			warn("%s: partial write: %d of %d bytes",
595 			     hostname, cc, i);
596 		}
597 	}
598 	ntransmitted++;
599 	if (!(options & F_QUIET) && options & F_FLOOD)
600 		(void)write(STDOUT_FILENO, &DOT, 1);
601 }
602 
603 /*
604  * pr_pack --
605  *	Print out the packet, if it came from us.  This logic is necessary
606  * because ALL readers of the ICMP socket get a copy of ALL ICMP packets
607  * which arrive ('tis only fair).  This permits multiple copies of this
608  * program to be run without having intermingled output (or statistics!).
609  */
610 static void
611 pr_pack(buf, cc, from)
612 	char *buf;
613 	int cc;
614 	struct sockaddr_in *from;
615 {
616 	register struct icmp *icp;
617 	register u_long l;
618 	register int i, j;
619 	register u_char *cp,*dp;
620 	static int old_rrlen;
621 	static char old_rr[MAX_IPOPTLEN];
622 	struct ip *ip;
623 	struct timeval tv, *tp;
624 	double triptime;
625 	int hlen, dupflag;
626 
627 	(void)gettimeofday(&tv, (struct timezone *)NULL);
628 
629 	/* Check the IP header */
630 	ip = (struct ip *)buf;
631 	hlen = ip->ip_hl << 2;
632 	if (cc < hlen + ICMP_MINLEN) {
633 		if (options & F_VERBOSE)
634 			warn("packet too short (%d bytes) from %s", cc,
635 			     inet_ntoa(from->sin_addr));
636 		return;
637 	}
638 
639 	/* Now the ICMP part */
640 	cc -= hlen;
641 	icp = (struct icmp *)(buf + hlen);
642 	if (icp->icmp_type == ICMP_ECHOREPLY) {
643 		if (icp->icmp_id != ident)
644 			return;			/* 'Twas not our ECHO */
645 		++nreceived;
646 		triptime = 0.0;
647 		if (timing) {
648 #ifndef icmp_data
649 			tp = (struct timeval *)&icp->icmp_ip;
650 #else
651 			tp = (struct timeval *)icp->icmp_data;
652 #endif
653 			tvsub(&tv, tp);
654 			triptime = ((double)tv.tv_sec) * 1000.0 +
655 			    ((double)tv.tv_usec) / 1000.0;
656 			tsum += triptime;
657 			tsumsq += triptime * triptime;
658 			if (triptime < tmin)
659 				tmin = triptime;
660 			if (triptime > tmax)
661 				tmax = triptime;
662 		}
663 
664 		if (TST(icp->icmp_seq % mx_dup_ck)) {
665 			++nrepeats;
666 			--nreceived;
667 			dupflag = 1;
668 		} else {
669 			SET(icp->icmp_seq % mx_dup_ck);
670 			dupflag = 0;
671 		}
672 
673 		if (options & F_QUIET)
674 			return;
675 
676 		if (options & F_FLOOD)
677 			(void)write(STDOUT_FILENO, &BSPACE, 1);
678 		else {
679 			(void)printf("%d bytes from %s: icmp_seq=%u", cc,
680 			   inet_ntoa(*(struct in_addr *)&from->sin_addr.s_addr),
681 			   icp->icmp_seq);
682 			(void)printf(" ttl=%d", ip->ip_ttl);
683 			if (timing)
684 				(void)printf(" time=%.3f ms", triptime);
685 			if (dupflag)
686 				(void)printf(" (DUP!)");
687 			if (options & F_AUDIBLE)
688 				(void)printf("\a");
689 			/* check the data */
690 			cp = (u_char*)&icp->icmp_data[8];
691 			dp = &outpack[8 + sizeof(struct timeval)];
692 			for (i = 8; i < datalen; ++i, ++cp, ++dp) {
693 				if (*cp != *dp) {
694 	(void)printf("\nwrong data byte #%d should be 0x%x but was 0x%x",
695 	    i, *dp, *cp);
696 					cp = (u_char*)&icp->icmp_data[0];
697 					for (i = 8; i < datalen; ++i, ++cp) {
698 						if ((i % 32) == 8)
699 							(void)printf("\n\t");
700 						(void)printf("%x ", *cp);
701 					}
702 					break;
703 				}
704 			}
705 		}
706 	} else {
707 		/*
708 		 * We've got something other than an ECHOREPLY.
709 		 * See if it's a reply to something that we sent.
710 		 * We can compare IP destination, protocol,
711 		 * and ICMP type and ID.
712 		 *
713 		 * Only print all the error messages if we are running
714 		 * as root to avoid leaking information not normally
715 		 * available to those not running as root.
716 		 */
717 #ifndef icmp_data
718 		struct ip *oip = &icp->icmp_ip;
719 #else
720 		struct ip *oip = (struct ip *)icp->icmp_data;
721 #endif
722 		struct icmp *oicmp = (struct icmp *)(oip + 1);
723 
724 		if (((options & F_VERBOSE) && uid == 0) ||
725 		    (!(options & F_QUIET2) &&
726 		     (oip->ip_dst.s_addr ==
727 			 ((struct sockaddr_in *)&whereto)->sin_addr.s_addr) &&
728 		     (oip->ip_p == IPPROTO_ICMP) &&
729 		     (oicmp->icmp_type == ICMP_ECHO) &&
730 		     (oicmp->icmp_id == ident))) {
731 		    (void)printf("%d bytes from %s: ", cc,
732 			pr_addr(from->sin_addr));
733 		    pr_icmph(icp);
734 		} else
735 		    return;
736 	}
737 
738 	/* Display any IP options */
739 	cp = (u_char *)buf + sizeof(struct ip);
740 
741 	for (; hlen > (int)sizeof(struct ip); --hlen, ++cp)
742 		switch (*cp) {
743 		case IPOPT_EOL:
744 			hlen = 0;
745 			break;
746 		case IPOPT_LSRR:
747 			(void)printf("\nLSRR: ");
748 			hlen -= 2;
749 			j = *++cp;
750 			++cp;
751 			if (j > IPOPT_MINOFF)
752 				for (;;) {
753 					l = *++cp;
754 					l = (l<<8) + *++cp;
755 					l = (l<<8) + *++cp;
756 					l = (l<<8) + *++cp;
757 					if (l == 0) {
758 						printf("\t0.0.0.0");
759 					} else {
760 						struct in_addr ina;
761 						ina.s_addr = ntohl(l);
762 						printf("\t%s", pr_addr(ina));
763 					}
764 				hlen -= 4;
765 				j -= 4;
766 				if (j <= IPOPT_MINOFF)
767 					break;
768 				(void)putchar('\n');
769 			}
770 			break;
771 		case IPOPT_RR:
772 			j = *++cp;		/* get length */
773 			i = *++cp;		/* and pointer */
774 			hlen -= 2;
775 			if (i > j)
776 				i = j;
777 			i -= IPOPT_MINOFF;
778 			if (i <= 0)
779 				continue;
780 			if (i == old_rrlen
781 			    && cp == (u_char *)buf + sizeof(struct ip) + 2
782 			    && !bcmp((char *)cp, old_rr, i)
783 			    && !(options & F_FLOOD)) {
784 				(void)printf("\t(same route)");
785 				i = ((i + 3) / 4) * 4;
786 				hlen -= i;
787 				cp += i;
788 				break;
789 			}
790 			old_rrlen = i;
791 			bcopy((char *)cp, old_rr, i);
792 			(void)printf("\nRR: ");
793 			for (;;) {
794 				l = *++cp;
795 				l = (l<<8) + *++cp;
796 				l = (l<<8) + *++cp;
797 				l = (l<<8) + *++cp;
798 				if (l == 0) {
799 					printf("\t0.0.0.0");
800 				} else {
801 					struct in_addr ina;
802 					ina.s_addr = ntohl(l);
803 					printf("\t%s", pr_addr(ina));
804 				}
805 				hlen -= 4;
806 				i -= 4;
807 				if (i <= 0)
808 					break;
809 				(void)putchar('\n');
810 			}
811 			break;
812 		case IPOPT_NOP:
813 			(void)printf("\nNOP");
814 			break;
815 		default:
816 			(void)printf("\nunknown option %x", *cp);
817 			break;
818 		}
819 	if (!(options & F_FLOOD)) {
820 		(void)putchar('\n');
821 		(void)fflush(stdout);
822 	}
823 }
824 
825 /*
826  * in_cksum --
827  *	Checksum routine for Internet Protocol family headers (C Version)
828  */
829 u_short
830 in_cksum(addr, len)
831 	u_short *addr;
832 	int len;
833 {
834 	register int nleft = len;
835 	register u_short *w = addr;
836 	register int sum = 0;
837 	u_short answer = 0;
838 
839 	/*
840 	 * Our algorithm is simple, using a 32 bit accumulator (sum), we add
841 	 * sequential 16 bit words to it, and at the end, fold back all the
842 	 * carry bits from the top 16 bits into the lower 16 bits.
843 	 */
844 	while (nleft > 1)  {
845 		sum += *w++;
846 		nleft -= 2;
847 	}
848 
849 	/* mop up an odd byte, if necessary */
850 	if (nleft == 1) {
851 		*(u_char *)(&answer) = *(u_char *)w ;
852 		sum += answer;
853 	}
854 
855 	/* add back carry outs from top 16 bits to low 16 bits */
856 	sum = (sum >> 16) + (sum & 0xffff);	/* add hi 16 to low 16 */
857 	sum += (sum >> 16);			/* add carry */
858 	answer = ~sum;				/* truncate to 16 bits */
859 	return(answer);
860 }
861 
862 /*
863  * tvsub --
864  *	Subtract 2 timeval structs:  out = out - in.  Out is assumed to
865  * be >= in.
866  */
867 static void
868 tvsub(out, in)
869 	register struct timeval *out, *in;
870 {
871 	if ((out->tv_usec -= in->tv_usec) < 0) {
872 		--out->tv_sec;
873 		out->tv_usec += 1000000;
874 	}
875 	out->tv_sec -= in->tv_sec;
876 }
877 
878 /*
879  * status --
880  *	Print out statistics when SIGINFO is received.
881  */
882 
883 static void
884 status(sig)
885 	int sig;
886 {
887 	siginfo_p = 1;
888 }
889 
890 static void
891 check_status()
892 {
893 	if (siginfo_p) {
894 		siginfo_p = 0;
895 		(void)fprintf(stderr,
896 	"\r%ld/%ld packets received (%.0f%%) %.3f min / %.3f avg / %.3f max\n",
897 		    nreceived, ntransmitted,
898 		    ntransmitted ? nreceived * 100.0 / ntransmitted : 0.0,
899 		    nreceived ? tmin : 0.0,
900 		    nreceived + nrepeats ? tsum / (nreceived + nrepeats) : tsum,
901 		    tmax);
902 	}
903 }
904 
905 /*
906  * finish --
907  *	Print out statistics, and give up.
908  */
909 static void
910 finish()
911 {
912 	struct termios ts;
913 
914 	(void)signal(SIGINT, SIG_IGN);
915 	(void)signal(SIGALRM, SIG_IGN);
916 	(void)putchar('\n');
917 	(void)fflush(stdout);
918 	(void)printf("--- %s ping statistics ---\n", hostname);
919 	(void)printf("%ld packets transmitted, ", ntransmitted);
920 	(void)printf("%ld packets received, ", nreceived);
921 	if (nrepeats)
922 		(void)printf("+%ld duplicates, ", nrepeats);
923 	if (ntransmitted)
924 		if (nreceived > ntransmitted)
925 			(void)printf("-- somebody's printing up packets!");
926 		else
927 			(void)printf("%d%% packet loss",
928 			    (int) (((ntransmitted - nreceived) * 100) /
929 			    ntransmitted));
930 	(void)putchar('\n');
931 	if (nreceived && timing) {
932 		double n = nreceived + nrepeats;
933 		double avg = tsum / n;
934 		double vari = tsumsq / n - avg * avg;
935 		printf("round-trip min/avg/max/stddev = "
936 		       "%.3f/%.3f/%.3f/%.3f ms\n",
937 		    tmin, avg, tmax, sqrt(vari));
938 	}
939 	if (reset_kerninfo && tcgetattr(STDOUT_FILENO, &ts) != -1) {
940 		ts.c_lflag &= ~NOKERNINFO;
941 		tcsetattr(STDOUT_FILENO, TCSANOW, &ts);
942 	}
943 
944 	if (nreceived)
945 		exit(0);
946 	else
947 		exit(2);
948 }
949 
950 #ifdef notdef
951 static char *ttab[] = {
952 	"Echo Reply",		/* ip + seq + udata */
953 	"Dest Unreachable",	/* net, host, proto, port, frag, sr + IP */
954 	"Source Quench",	/* IP */
955 	"Redirect",		/* redirect type, gateway, + IP  */
956 	"Echo",
957 	"Time Exceeded",	/* transit, frag reassem + IP */
958 	"Parameter Problem",	/* pointer + IP */
959 	"Timestamp",		/* id + seq + three timestamps */
960 	"Timestamp Reply",	/* " */
961 	"Info Request",		/* id + sq */
962 	"Info Reply"		/* " */
963 };
964 #endif
965 
966 /*
967  * pr_icmph --
968  *	Print a descriptive string about an ICMP header.
969  */
970 static void
971 pr_icmph(icp)
972 	struct icmp *icp;
973 {
974 	switch(icp->icmp_type) {
975 	case ICMP_ECHOREPLY:
976 		(void)printf("Echo Reply\n");
977 		/* XXX ID + Seq + Data */
978 		break;
979 	case ICMP_UNREACH:
980 		switch(icp->icmp_code) {
981 		case ICMP_UNREACH_NET:
982 			(void)printf("Destination Net Unreachable\n");
983 			break;
984 		case ICMP_UNREACH_HOST:
985 			(void)printf("Destination Host Unreachable\n");
986 			break;
987 		case ICMP_UNREACH_PROTOCOL:
988 			(void)printf("Destination Protocol Unreachable\n");
989 			break;
990 		case ICMP_UNREACH_PORT:
991 			(void)printf("Destination Port Unreachable\n");
992 			break;
993 		case ICMP_UNREACH_NEEDFRAG:
994 			(void)printf("frag needed and DF set (MTU %d)\n",
995 					ntohs(icp->icmp_nextmtu));
996 			break;
997 		case ICMP_UNREACH_SRCFAIL:
998 			(void)printf("Source Route Failed\n");
999 			break;
1000 		case ICMP_UNREACH_FILTER_PROHIB:
1001 			(void)printf("Communication prohibited by filter\n");
1002 			break;
1003 		default:
1004 			(void)printf("Dest Unreachable, Bad Code: %d\n",
1005 			    icp->icmp_code);
1006 			break;
1007 		}
1008 		/* Print returned IP header information */
1009 #ifndef icmp_data
1010 		pr_retip(&icp->icmp_ip);
1011 #else
1012 		pr_retip((struct ip *)icp->icmp_data);
1013 #endif
1014 		break;
1015 	case ICMP_SOURCEQUENCH:
1016 		(void)printf("Source Quench\n");
1017 #ifndef icmp_data
1018 		pr_retip(&icp->icmp_ip);
1019 #else
1020 		pr_retip((struct ip *)icp->icmp_data);
1021 #endif
1022 		break;
1023 	case ICMP_REDIRECT:
1024 		switch(icp->icmp_code) {
1025 		case ICMP_REDIRECT_NET:
1026 			(void)printf("Redirect Network");
1027 			break;
1028 		case ICMP_REDIRECT_HOST:
1029 			(void)printf("Redirect Host");
1030 			break;
1031 		case ICMP_REDIRECT_TOSNET:
1032 			(void)printf("Redirect Type of Service and Network");
1033 			break;
1034 		case ICMP_REDIRECT_TOSHOST:
1035 			(void)printf("Redirect Type of Service and Host");
1036 			break;
1037 		default:
1038 			(void)printf("Redirect, Bad Code: %d", icp->icmp_code);
1039 			break;
1040 		}
1041 		(void)printf("(New addr: %s)\n", inet_ntoa(icp->icmp_gwaddr));
1042 #ifndef icmp_data
1043 		pr_retip(&icp->icmp_ip);
1044 #else
1045 		pr_retip((struct ip *)icp->icmp_data);
1046 #endif
1047 		break;
1048 	case ICMP_ECHO:
1049 		(void)printf("Echo Request\n");
1050 		/* XXX ID + Seq + Data */
1051 		break;
1052 	case ICMP_TIMXCEED:
1053 		switch(icp->icmp_code) {
1054 		case ICMP_TIMXCEED_INTRANS:
1055 			(void)printf("Time to live exceeded\n");
1056 			break;
1057 		case ICMP_TIMXCEED_REASS:
1058 			(void)printf("Frag reassembly time exceeded\n");
1059 			break;
1060 		default:
1061 			(void)printf("Time exceeded, Bad Code: %d\n",
1062 			    icp->icmp_code);
1063 			break;
1064 		}
1065 #ifndef icmp_data
1066 		pr_retip(&icp->icmp_ip);
1067 #else
1068 		pr_retip((struct ip *)icp->icmp_data);
1069 #endif
1070 		break;
1071 	case ICMP_PARAMPROB:
1072 		(void)printf("Parameter problem: pointer = 0x%02x\n",
1073 		    icp->icmp_hun.ih_pptr);
1074 #ifndef icmp_data
1075 		pr_retip(&icp->icmp_ip);
1076 #else
1077 		pr_retip((struct ip *)icp->icmp_data);
1078 #endif
1079 		break;
1080 	case ICMP_TSTAMP:
1081 		(void)printf("Timestamp\n");
1082 		/* XXX ID + Seq + 3 timestamps */
1083 		break;
1084 	case ICMP_TSTAMPREPLY:
1085 		(void)printf("Timestamp Reply\n");
1086 		/* XXX ID + Seq + 3 timestamps */
1087 		break;
1088 	case ICMP_IREQ:
1089 		(void)printf("Information Request\n");
1090 		/* XXX ID + Seq */
1091 		break;
1092 	case ICMP_IREQREPLY:
1093 		(void)printf("Information Reply\n");
1094 		/* XXX ID + Seq */
1095 		break;
1096 	case ICMP_MASKREQ:
1097 		(void)printf("Address Mask Request\n");
1098 		break;
1099 	case ICMP_MASKREPLY:
1100 		(void)printf("Address Mask Reply\n");
1101 		break;
1102 	case ICMP_ROUTERADVERT:
1103 		(void)printf("Router Advertisement\n");
1104 		break;
1105 	case ICMP_ROUTERSOLICIT:
1106 		(void)printf("Router Solicitation\n");
1107 		break;
1108 	default:
1109 		(void)printf("Bad ICMP type: %d\n", icp->icmp_type);
1110 	}
1111 }
1112 
1113 /*
1114  * pr_iph --
1115  *	Print an IP header with options.
1116  */
1117 static void
1118 pr_iph(ip)
1119 	struct ip *ip;
1120 {
1121 	int hlen;
1122 	u_char *cp;
1123 
1124 	hlen = ip->ip_hl << 2;
1125 	cp = (u_char *)ip + 20;		/* point to options */
1126 
1127 	(void)printf("Vr HL TOS  Len   ID Flg  off TTL Pro  cks      Src      Dst\n");
1128 	(void)printf(" %1x  %1x  %02x %04x %04x",
1129 	    ip->ip_v, ip->ip_hl, ip->ip_tos, ntohs(ip->ip_len),
1130 	    ntohs(ip->ip_id));
1131 	(void)printf("   %1lx %04lx", (ntohl(ip->ip_off) & 0xe000) >> 13,
1132 	    ntohl(ip->ip_off) & 0x1fff);
1133 	(void)printf("  %02x  %02x %04x", ip->ip_ttl, ip->ip_p,
1134 							    ntohs(ip->ip_sum));
1135 	(void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_src.s_addr));
1136 	(void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_dst.s_addr));
1137 	/* dump any option bytes */
1138 	while (hlen-- > 20) {
1139 		(void)printf("%02x", *cp++);
1140 	}
1141 	(void)putchar('\n');
1142 }
1143 
1144 /*
1145  * pr_addr --
1146  *	Return an ascii host address as a dotted quad and optionally with
1147  * a hostname.
1148  */
1149 static char *
1150 pr_addr(ina)
1151 	struct in_addr ina;
1152 {
1153 	struct hostent *hp;
1154 	static char buf[16 + 3 + MAXHOSTNAMELEN];
1155 
1156 	if ((options & F_NUMERIC) ||
1157 	    !(hp = gethostbyaddr((char *)&ina, 4, AF_INET)))
1158 		return inet_ntoa(ina);
1159 	else
1160 		(void)snprintf(buf, sizeof(buf), "%s (%s)", hp->h_name,
1161 		    inet_ntoa(ina));
1162 	return(buf);
1163 }
1164 
1165 /*
1166  * pr_retip --
1167  *	Dump some info on a returned (via ICMP) IP packet.
1168  */
1169 static void
1170 pr_retip(ip)
1171 	struct ip *ip;
1172 {
1173 	int hlen;
1174 	u_char *cp;
1175 
1176 	pr_iph(ip);
1177 	hlen = ip->ip_hl << 2;
1178 	cp = (u_char *)ip + hlen;
1179 
1180 	if (ip->ip_p == 6)
1181 		(void)printf("TCP: from port %u, to port %u (decimal)\n",
1182 		    (*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3)));
1183 	else if (ip->ip_p == 17)
1184 		(void)printf("UDP: from port %u, to port %u (decimal)\n",
1185 			(*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3)));
1186 }
1187 
1188 static void
1189 fill(bp, patp)
1190 	char *bp, *patp;
1191 {
1192 	register int ii, jj, kk;
1193 	int pat[16];
1194 	char *cp;
1195 
1196 	for (cp = patp; *cp; cp++) {
1197 		if (!isxdigit(*cp))
1198 			errx(EX_USAGE,
1199 			     "patterns must be specified as hex digits");
1200 
1201 	}
1202 	ii = sscanf(patp,
1203 	    "%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x",
1204 	    &pat[0], &pat[1], &pat[2], &pat[3], &pat[4], &pat[5], &pat[6],
1205 	    &pat[7], &pat[8], &pat[9], &pat[10], &pat[11], &pat[12],
1206 	    &pat[13], &pat[14], &pat[15]);
1207 
1208 	if (ii > 0)
1209 		for (kk = 0;
1210 		    kk <= MAXPACKET - (8 + sizeof(struct timeval) + ii);
1211 		    kk += ii)
1212 			for (jj = 0; jj < ii; ++jj)
1213 				bp[jj + kk] = pat[jj];
1214 	if (!(options & F_QUIET)) {
1215 		(void)printf("PATTERN: 0x");
1216 		for (jj = 0; jj < ii; ++jj)
1217 			(void)printf("%02x", bp[jj] & 0xFF);
1218 		(void)printf("\n");
1219 	}
1220 }
1221 
1222 static void
1223 usage(argv0)
1224 	const char *argv0;
1225 {
1226 	if (strrchr(argv0,'/'))
1227 		argv0 = strrchr(argv0,'/') + 1;
1228 	fprintf(stderr,
1229 		"usage: %s [-QRadfnqrv] [-c count] [-i wait] [-l preload] "
1230 		"[-p pattern]\n       [-s packetsize] "
1231 		"[host | [-L] [-I iface] [-T ttl] mcast-group]\n",
1232 		argv0);
1233 	exit(EX_USAGE);
1234 }
1235