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