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