ping.c revision 27508
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.24 1997/07/13 06:16:44 sef 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	MAXIPLEN	60
97#define	MAXICMPLEN	76
98#define	MAXPACKET	(65536 - 60 - 8)/* max packet size */
99#define	MAXWAIT		10		/* max seconds to wait for response */
100#define	NROUTES		9		/* number of record route slots */
101#define	FLOOD_BACKOFF	20000		/* usecs to back off if flooding */
102					/* reports we are out of buffer space */
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 */
111int 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)
133int mx_dup_ck = MAX_DUP_CHK;
134char rcvd_tbl[MAX_DUP_CHK / 8];
135
136struct sockaddr whereto;	/* who to ping */
137int datalen = DEFDATALEN;
138int s;				/* socket file descriptor */
139u_char outpack[MAXPACKET];
140char BSPACE = '\b';		/* characters written for flood */
141char DOT = '.';
142char *hostname;
143int ident;			/* process id to identify our packets */
144int uid;			/* cached uid for micro-optimization */
145
146/* counters */
147long npackets;			/* max packets to transmit */
148long nreceived;			/* # of packets we got back */
149long nrepeats;			/* number of duplicates */
150long ntransmitted;		/* sequence # for outbound packets = #sent */
151int interval = 1;		/* interval between packets */
152int finish_up = 0;		/* We've been told to finish up */
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
161int reset_kerninfo;
162sig_atomic_t siginfo_p;
163
164static void fill(char *, char *);
165static u_short in_cksum(u_short *, int);
166static void catcher(int sig);
167static void check_status(void);
168static void stopit(int);
169static void finish(int) __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 tvsub(struct timeval *, struct timeval *);
178static void usage(const char *) __dead2;
179
180int
181main(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 == 0) {
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(0);
491	/* NOTREACHED */
492	exit(0);	/* Make the compiler happy */
493}
494
495/*
496 * Stopit --
497 *
498 * set the global bit that cause everything to quit..
499 * do rNOT quit and exit from the signal handler!
500 */
501void
502stopit(int ignored)
503{
504	finish_up = 1;
505}
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 */
518static void
519catcher(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 */
555static void
556pinger(void)
557{
558	register struct icmp *icp;
559	register int cc;
560	int i;
561
562	icp = (struct icmp *)outpack;
563	icp->icmp_type = ICMP_ECHO;
564	icp->icmp_code = 0;
565	icp->icmp_cksum = 0;
566	icp->icmp_seq = ntransmitted;
567	icp->icmp_id = ident;			/* ID */
568
569	CLR(icp->icmp_seq % mx_dup_ck);
570
571	if (timing)
572		(void)gettimeofday((struct timeval *)&outpack[8],
573		    (struct timezone *)NULL);
574
575	cc = datalen + 8;			/* skips ICMP portion */
576
577	/* compute ICMP checksum here */
578	icp->icmp_cksum = in_cksum((u_short *)icp, cc);
579
580	i = sendto(s, (char *)outpack, cc, 0, &whereto,
581	    sizeof(struct sockaddr));
582
583	if (i < 0 || i != cc)  {
584		if (i < 0) {
585			if ((options & F_FLOOD) && (errno == ENOBUFS)) {
586				usleep(FLOOD_BACKOFF);
587				return;
588			}
589			warn("sendto");
590		} else {
591			warn("%s: partial write: %d of %d bytes",
592			     hostname, cc, i);
593		}
594	} else {
595		ntransmitted++; /* only count those that made it out */
596	}
597	if (!(options & F_QUIET) && options & F_FLOOD)
598		(void)write(STDOUT_FILENO, &DOT, 1);
599}
600
601/*
602 * pr_pack --
603 *	Print out the packet, if it came from us.  This logic is necessary
604 * because ALL readers of the ICMP socket get a copy of ALL ICMP packets
605 * which arrive ('tis only fair).  This permits multiple copies of this
606 * program to be run without having intermingled output (or statistics!).
607 */
608static void
609pr_pack(buf, cc, from)
610	char *buf;
611	int cc;
612	struct sockaddr_in *from;
613{
614	register struct icmp *icp;
615	register u_long l;
616	register int i, j;
617	register u_char *cp,*dp;
618	static int old_rrlen;
619	static char old_rr[MAX_IPOPTLEN];
620	struct ip *ip;
621	struct timeval tv, *tp;
622	double triptime = 0.0;
623	int hlen, dupflag;
624
625	(void)gettimeofday(&tv, (struct timezone *)NULL);
626
627	/* Check the IP header */
628	ip = (struct ip *)buf;
629	hlen = ip->ip_hl << 2;
630	if (cc < hlen + ICMP_MINLEN) {
631		if (options & F_VERBOSE)
632			warn("packet too short (%d bytes) from %s", cc,
633			     inet_ntoa(from->sin_addr));
634		return;
635	}
636
637	/* Now the ICMP part */
638	cc -= hlen;
639	icp = (struct icmp *)(buf + hlen);
640	if (icp->icmp_type == ICMP_ECHOREPLY) {
641		if (icp->icmp_id != ident)
642			return;			/* 'Twas not our ECHO */
643		++nreceived;
644		if (timing) {
645#ifndef icmp_data
646			tp = (struct timeval *)&icp->icmp_ip;
647#else
648			tp = (struct timeval *)icp->icmp_data;
649#endif
650			tvsub(&tv, tp);
651			triptime = ((double)tv.tv_sec) * 1000.0 +
652			    ((double)tv.tv_usec) / 1000.0;
653			tsum += triptime;
654			tsumsq += triptime * triptime;
655			if (triptime < tmin)
656				tmin = triptime;
657			if (triptime > tmax)
658				tmax = triptime;
659		}
660
661		if (TST(icp->icmp_seq % mx_dup_ck)) {
662			++nrepeats;
663			--nreceived;
664			dupflag = 1;
665		} else {
666			SET(icp->icmp_seq % mx_dup_ck);
667			dupflag = 0;
668		}
669
670		if (options & F_QUIET)
671			return;
672
673		if (options & F_FLOOD)
674			(void)write(STDOUT_FILENO, &BSPACE, 1);
675		else {
676			(void)printf("%d bytes from %s: icmp_seq=%u", cc,
677			   inet_ntoa(*(struct in_addr *)&from->sin_addr.s_addr),
678			   icp->icmp_seq);
679			(void)printf(" ttl=%d", ip->ip_ttl);
680			if (timing)
681				(void)printf(" time=%.3f ms", triptime);
682			if (dupflag)
683				(void)printf(" (DUP!)");
684			if (options & F_AUDIBLE)
685				(void)printf("\a");
686			/* check the data */
687			cp = (u_char*)&icp->icmp_data[8];
688			dp = &outpack[8 + sizeof(struct timeval)];
689			for (i = 8; i < datalen; ++i, ++cp, ++dp) {
690				if (*cp != *dp) {
691	(void)printf("\nwrong data byte #%d should be 0x%x but was 0x%x",
692	    i, *dp, *cp);
693					cp = (u_char*)&icp->icmp_data[0];
694					for (i = 8; i < datalen; ++i, ++cp) {
695						if ((i % 32) == 8)
696							(void)printf("\n\t");
697						(void)printf("%x ", *cp);
698					}
699					break;
700				}
701			}
702		}
703	} else {
704		/*
705		 * We've got something other than an ECHOREPLY.
706		 * See if it's a reply to something that we sent.
707		 * We can compare IP destination, protocol,
708		 * and ICMP type and ID.
709		 *
710		 * Only print all the error messages if we are running
711		 * as root to avoid leaking information not normally
712		 * available to those not running as root.
713		 */
714#ifndef icmp_data
715		struct ip *oip = &icp->icmp_ip;
716#else
717		struct ip *oip = (struct ip *)icp->icmp_data;
718#endif
719		struct icmp *oicmp = (struct icmp *)(oip + 1);
720
721		if (((options & F_VERBOSE) && uid == 0) ||
722		    (!(options & F_QUIET2) &&
723		     (oip->ip_dst.s_addr ==
724			 ((struct sockaddr_in *)&whereto)->sin_addr.s_addr) &&
725		     (oip->ip_p == IPPROTO_ICMP) &&
726		     (oicmp->icmp_type == ICMP_ECHO) &&
727		     (oicmp->icmp_id == ident))) {
728		    (void)printf("%d bytes from %s: ", cc,
729			pr_addr(from->sin_addr));
730		    pr_icmph(icp);
731		} else
732		    return;
733	}
734
735	/* Display any IP options */
736	cp = (u_char *)buf + sizeof(struct ip);
737
738	for (; hlen > (int)sizeof(struct ip); --hlen, ++cp)
739		switch (*cp) {
740		case IPOPT_EOL:
741			hlen = 0;
742			break;
743		case IPOPT_LSRR:
744			(void)printf("\nLSRR: ");
745			hlen -= 2;
746			j = *++cp;
747			++cp;
748			if (j > IPOPT_MINOFF)
749				for (;;) {
750					l = *++cp;
751					l = (l<<8) + *++cp;
752					l = (l<<8) + *++cp;
753					l = (l<<8) + *++cp;
754					if (l == 0) {
755						printf("\t0.0.0.0");
756					} else {
757						struct in_addr ina;
758						ina.s_addr = ntohl(l);
759						printf("\t%s", pr_addr(ina));
760					}
761				hlen -= 4;
762				j -= 4;
763				if (j <= IPOPT_MINOFF)
764					break;
765				(void)putchar('\n');
766			}
767			break;
768		case IPOPT_RR:
769			j = *++cp;		/* get length */
770			i = *++cp;		/* and pointer */
771			hlen -= 2;
772			if (i > j)
773				i = j;
774			i -= IPOPT_MINOFF;
775			if (i <= 0)
776				continue;
777			if (i == old_rrlen
778			    && cp == (u_char *)buf + sizeof(struct ip) + 2
779			    && !bcmp((char *)cp, old_rr, i)
780			    && !(options & F_FLOOD)) {
781				(void)printf("\t(same route)");
782				i = ((i + 3) / 4) * 4;
783				hlen -= i;
784				cp += i;
785				break;
786			}
787			old_rrlen = i;
788			bcopy((char *)cp, old_rr, i);
789			(void)printf("\nRR: ");
790			for (;;) {
791				l = *++cp;
792				l = (l<<8) + *++cp;
793				l = (l<<8) + *++cp;
794				l = (l<<8) + *++cp;
795				if (l == 0) {
796					printf("\t0.0.0.0");
797				} else {
798					struct in_addr ina;
799					ina.s_addr = ntohl(l);
800					printf("\t%s", pr_addr(ina));
801				}
802				hlen -= 4;
803				i -= 4;
804				if (i <= 0)
805					break;
806				(void)putchar('\n');
807			}
808			break;
809		case IPOPT_NOP:
810			(void)printf("\nNOP");
811			break;
812		default:
813			(void)printf("\nunknown option %x", *cp);
814			break;
815		}
816	if (!(options & F_FLOOD)) {
817		(void)putchar('\n');
818		(void)fflush(stdout);
819	}
820}
821
822/*
823 * in_cksum --
824 *	Checksum routine for Internet Protocol family headers (C Version)
825 */
826u_short
827in_cksum(addr, len)
828	u_short *addr;
829	int len;
830{
831	register int nleft = len;
832	register u_short *w = addr;
833	register int sum = 0;
834	u_short answer = 0;
835
836	/*
837	 * Our algorithm is simple, using a 32 bit accumulator (sum), we add
838	 * sequential 16 bit words to it, and at the end, fold back all the
839	 * carry bits from the top 16 bits into the lower 16 bits.
840	 */
841	while (nleft > 1)  {
842		sum += *w++;
843		nleft -= 2;
844	}
845
846	/* mop up an odd byte, if necessary */
847	if (nleft == 1) {
848		*(u_char *)(&answer) = *(u_char *)w ;
849		sum += answer;
850	}
851
852	/* add back carry outs from top 16 bits to low 16 bits */
853	sum = (sum >> 16) + (sum & 0xffff);	/* add hi 16 to low 16 */
854	sum += (sum >> 16);			/* add carry */
855	answer = ~sum;				/* truncate to 16 bits */
856	return(answer);
857}
858
859/*
860 * tvsub --
861 *	Subtract 2 timeval structs:  out = out - in.  Out is assumed to
862 * be >= in.
863 */
864static void
865tvsub(out, in)
866	register struct timeval *out, *in;
867{
868	if ((out->tv_usec -= in->tv_usec) < 0) {
869		--out->tv_sec;
870		out->tv_usec += 1000000;
871	}
872	out->tv_sec -= in->tv_sec;
873}
874
875/*
876 * status --
877 *	Print out statistics when SIGINFO is received.
878 */
879
880static void
881status(sig)
882	int sig;
883{
884	siginfo_p = 1;
885}
886
887static void
888check_status()
889{
890	if (siginfo_p) {
891		siginfo_p = 0;
892		(void)fprintf(stderr,
893	"\r%ld/%ld packets received (%.0f%%) %.3f min / %.3f avg / %.3f max\n",
894		    nreceived, ntransmitted,
895		    ntransmitted ? nreceived * 100.0 / ntransmitted : 0.0,
896		    nreceived ? tmin : 0.0,
897		    nreceived + nrepeats ? tsum / (nreceived + nrepeats) : tsum,
898		    tmax);
899	}
900}
901
902/*
903 * finish --
904 *	Print out statistics, and give up.
905 */
906static void
907finish(int sig)
908{
909	struct termios ts;
910
911	(void)signal(SIGINT, SIG_IGN);
912	(void)signal(SIGALRM, SIG_IGN);
913	(void)putchar('\n');
914	(void)fflush(stdout);
915	(void)printf("--- %s ping statistics ---\n", hostname);
916	(void)printf("%ld packets transmitted, ", ntransmitted);
917	(void)printf("%ld packets received, ", nreceived);
918	if (nrepeats)
919		(void)printf("+%ld duplicates, ", nrepeats);
920	if (ntransmitted)
921		if (nreceived > ntransmitted)
922			(void)printf("-- somebody's printing up packets!");
923		else
924			(void)printf("%d%% packet loss",
925			    (int) (((ntransmitted - nreceived) * 100) /
926			    ntransmitted));
927	(void)putchar('\n');
928	if (nreceived && timing) {
929		double n = nreceived + nrepeats;
930		double avg = tsum / n;
931		double vari = tsumsq / n - avg * avg;
932		printf("round-trip min/avg/max/stddev = "
933		       "%.3f/%.3f/%.3f/%.3f ms\n",
934		    tmin, avg, tmax, sqrt(vari));
935	}
936	if (reset_kerninfo && tcgetattr(STDOUT_FILENO, &ts) != -1) {
937		ts.c_lflag &= ~NOKERNINFO;
938		tcsetattr(STDOUT_FILENO, TCSANOW, &ts);
939	}
940
941	if (nreceived)
942		exit(0);
943	else
944		exit(2);
945}
946
947#ifdef notdef
948static char *ttab[] = {
949	"Echo Reply",		/* ip + seq + udata */
950	"Dest Unreachable",	/* net, host, proto, port, frag, sr + IP */
951	"Source Quench",	/* IP */
952	"Redirect",		/* redirect type, gateway, + IP  */
953	"Echo",
954	"Time Exceeded",	/* transit, frag reassem + IP */
955	"Parameter Problem",	/* pointer + IP */
956	"Timestamp",		/* id + seq + three timestamps */
957	"Timestamp Reply",	/* " */
958	"Info Request",		/* id + sq */
959	"Info Reply"		/* " */
960};
961#endif
962
963/*
964 * pr_icmph --
965 *	Print a descriptive string about an ICMP header.
966 */
967static void
968pr_icmph(icp)
969	struct icmp *icp;
970{
971	switch(icp->icmp_type) {
972	case ICMP_ECHOREPLY:
973		(void)printf("Echo Reply\n");
974		/* XXX ID + Seq + Data */
975		break;
976	case ICMP_UNREACH:
977		switch(icp->icmp_code) {
978		case ICMP_UNREACH_NET:
979			(void)printf("Destination Net Unreachable\n");
980			break;
981		case ICMP_UNREACH_HOST:
982			(void)printf("Destination Host Unreachable\n");
983			break;
984		case ICMP_UNREACH_PROTOCOL:
985			(void)printf("Destination Protocol Unreachable\n");
986			break;
987		case ICMP_UNREACH_PORT:
988			(void)printf("Destination Port Unreachable\n");
989			break;
990		case ICMP_UNREACH_NEEDFRAG:
991			(void)printf("frag needed and DF set (MTU %d)\n",
992					icp->icmp_nextmtu);
993			break;
994		case ICMP_UNREACH_SRCFAIL:
995			(void)printf("Source Route Failed\n");
996			break;
997		case ICMP_UNREACH_FILTER_PROHIB:
998			(void)printf("Communication prohibited by filter\n");
999			break;
1000		default:
1001			(void)printf("Dest Unreachable, Bad Code: %d\n",
1002			    icp->icmp_code);
1003			break;
1004		}
1005		/* Print returned IP header information */
1006#ifndef icmp_data
1007		pr_retip(&icp->icmp_ip);
1008#else
1009		pr_retip((struct ip *)icp->icmp_data);
1010#endif
1011		break;
1012	case ICMP_SOURCEQUENCH:
1013		(void)printf("Source Quench\n");
1014#ifndef icmp_data
1015		pr_retip(&icp->icmp_ip);
1016#else
1017		pr_retip((struct ip *)icp->icmp_data);
1018#endif
1019		break;
1020	case ICMP_REDIRECT:
1021		switch(icp->icmp_code) {
1022		case ICMP_REDIRECT_NET:
1023			(void)printf("Redirect Network");
1024			break;
1025		case ICMP_REDIRECT_HOST:
1026			(void)printf("Redirect Host");
1027			break;
1028		case ICMP_REDIRECT_TOSNET:
1029			(void)printf("Redirect Type of Service and Network");
1030			break;
1031		case ICMP_REDIRECT_TOSHOST:
1032			(void)printf("Redirect Type of Service and Host");
1033			break;
1034		default:
1035			(void)printf("Redirect, Bad Code: %d", icp->icmp_code);
1036			break;
1037		}
1038		(void)printf("(New addr: 0x%08lx)\n", icp->icmp_gwaddr.s_addr);
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_ECHO:
1046		(void)printf("Echo Request\n");
1047		/* XXX ID + Seq + Data */
1048		break;
1049	case ICMP_TIMXCEED:
1050		switch(icp->icmp_code) {
1051		case ICMP_TIMXCEED_INTRANS:
1052			(void)printf("Time to live exceeded\n");
1053			break;
1054		case ICMP_TIMXCEED_REASS:
1055			(void)printf("Frag reassembly time exceeded\n");
1056			break;
1057		default:
1058			(void)printf("Time exceeded, Bad Code: %d\n",
1059			    icp->icmp_code);
1060			break;
1061		}
1062#ifndef icmp_data
1063		pr_retip(&icp->icmp_ip);
1064#else
1065		pr_retip((struct ip *)icp->icmp_data);
1066#endif
1067		break;
1068	case ICMP_PARAMPROB:
1069		(void)printf("Parameter problem: pointer = 0x%02x\n",
1070		    icp->icmp_hun.ih_pptr);
1071#ifndef icmp_data
1072		pr_retip(&icp->icmp_ip);
1073#else
1074		pr_retip((struct ip *)icp->icmp_data);
1075#endif
1076		break;
1077	case ICMP_TSTAMP:
1078		(void)printf("Timestamp\n");
1079		/* XXX ID + Seq + 3 timestamps */
1080		break;
1081	case ICMP_TSTAMPREPLY:
1082		(void)printf("Timestamp Reply\n");
1083		/* XXX ID + Seq + 3 timestamps */
1084		break;
1085	case ICMP_IREQ:
1086		(void)printf("Information Request\n");
1087		/* XXX ID + Seq */
1088		break;
1089	case ICMP_IREQREPLY:
1090		(void)printf("Information Reply\n");
1091		/* XXX ID + Seq */
1092		break;
1093	case ICMP_MASKREQ:
1094		(void)printf("Address Mask Request\n");
1095		break;
1096	case ICMP_MASKREPLY:
1097		(void)printf("Address Mask Reply\n");
1098		break;
1099	case ICMP_ROUTERADVERT:
1100		(void)printf("Router Advertisement\n");
1101		break;
1102	case ICMP_ROUTERSOLICIT:
1103		(void)printf("Router Solicitation\n");
1104		break;
1105	default:
1106		(void)printf("Bad ICMP type: %d\n", icp->icmp_type);
1107	}
1108}
1109
1110/*
1111 * pr_iph --
1112 *	Print an IP header with options.
1113 */
1114static void
1115pr_iph(ip)
1116	struct ip *ip;
1117{
1118	int hlen;
1119	u_char *cp;
1120
1121	hlen = ip->ip_hl << 2;
1122	cp = (u_char *)ip + 20;		/* point to options */
1123
1124	(void)printf("Vr HL TOS  Len   ID Flg  off TTL Pro  cks      Src      Dst\n");
1125	(void)printf(" %1x  %1x  %02x %04x %04x",
1126	    ip->ip_v, ip->ip_hl, ip->ip_tos, ntohs(ip->ip_len),
1127	    ntohs(ip->ip_id));
1128	(void)printf("   %1lx %04lx", (ntohl(ip->ip_off) & 0xe000) >> 13,
1129	    ntohl(ip->ip_off) & 0x1fff);
1130	(void)printf("  %02x  %02x %04x", ip->ip_ttl, ip->ip_p,
1131							    ntohs(ip->ip_sum));
1132	(void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_src.s_addr));
1133	(void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_dst.s_addr));
1134	/* dump any option bytes */
1135	while (hlen-- > 20) {
1136		(void)printf("%02x", *cp++);
1137	}
1138	(void)putchar('\n');
1139}
1140
1141/*
1142 * pr_addr --
1143 *	Return an ascii host address as a dotted quad and optionally with
1144 * a hostname.
1145 */
1146static char *
1147pr_addr(ina)
1148	struct in_addr ina;
1149{
1150	struct hostent *hp;
1151	static char buf[16 + 3 + MAXHOSTNAMELEN];
1152
1153	if ((options & F_NUMERIC) ||
1154	    !(hp = gethostbyaddr((char *)&ina, 4, AF_INET)))
1155		return inet_ntoa(ina);
1156	else
1157		(void)snprintf(buf, sizeof(buf), "%s (%s)", hp->h_name,
1158		    inet_ntoa(ina));
1159	return(buf);
1160}
1161
1162/*
1163 * pr_retip --
1164 *	Dump some info on a returned (via ICMP) IP packet.
1165 */
1166static void
1167pr_retip(ip)
1168	struct ip *ip;
1169{
1170	int hlen;
1171	u_char *cp;
1172
1173	pr_iph(ip);
1174	hlen = ip->ip_hl << 2;
1175	cp = (u_char *)ip + hlen;
1176
1177	if (ip->ip_p == 6)
1178		(void)printf("TCP: from port %u, to port %u (decimal)\n",
1179		    (*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3)));
1180	else if (ip->ip_p == 17)
1181		(void)printf("UDP: from port %u, to port %u (decimal)\n",
1182			(*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3)));
1183}
1184
1185static void
1186fill(bp, patp)
1187	char *bp, *patp;
1188{
1189	register int ii, jj, kk;
1190	int pat[16];
1191	char *cp;
1192
1193	for (cp = patp; *cp; cp++) {
1194		if (!isxdigit(*cp))
1195			errx(EX_USAGE,
1196			     "patterns must be specified as hex digits");
1197
1198	}
1199	ii = sscanf(patp,
1200	    "%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x",
1201	    &pat[0], &pat[1], &pat[2], &pat[3], &pat[4], &pat[5], &pat[6],
1202	    &pat[7], &pat[8], &pat[9], &pat[10], &pat[11], &pat[12],
1203	    &pat[13], &pat[14], &pat[15]);
1204
1205	if (ii > 0)
1206		for (kk = 0;
1207		    kk <= MAXPACKET - (8 + sizeof(struct timeval) + ii);
1208		    kk += ii)
1209			for (jj = 0; jj < ii; ++jj)
1210				bp[jj + kk] = pat[jj];
1211	if (!(options & F_QUIET)) {
1212		(void)printf("PATTERN: 0x");
1213		for (jj = 0; jj < ii; ++jj)
1214			(void)printf("%02x", bp[jj] & 0xFF);
1215		(void)printf("\n");
1216	}
1217}
1218
1219static void
1220usage(argv0)
1221	const char *argv0;
1222{
1223	if (strrchr(argv0,'/'))
1224		argv0 = strrchr(argv0,'/') + 1;
1225	fprintf(stderr,
1226		"usage: %s [-QRadfnqrv] [-c count] [-i wait] [-l preload] "
1227		"[-p pattern]\n       [-s packetsize] "
1228		"[host | [-L] [-I iface] [-T ttl] mcast-group]\n",
1229		argv0);
1230	exit(EX_USAGE);
1231}
1232