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