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