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