xref: /freebsd/sbin/ping/ping.c (revision 953a3198a35204535cc9d450f04da982a4fea59b)
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
38 static 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 static 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 */
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 double tmin = 999999999.0;	/* minimum round trip time */
137 double tmax = 0.0;		/* maximum round trip time */
138 double tsum = 0.0;		/* sum of all times, for doing average */
139 
140 int reset_kerninfo;
141 
142 char *pr_addr();
143 void catcher(), finish(), status();
144 
145 main(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  */
392 void
393 catcher()
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  */
421 pinger()
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  */
465 pr_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  */
651 in_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  */
688 tvsub(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 
703 void
704 status()
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  */
725 void
726 finish()
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 	if (nreceived)
759 		exit(0);
760 	else
761 		exit(2);
762 }
763 
764 #ifdef notdef
765 static char *ttab[] = {
766 	"Echo Reply",		/* ip + seq + udata */
767 	"Dest Unreachable",	/* net, host, proto, port, frag, sr + IP */
768 	"Source Quench",	/* IP */
769 	"Redirect",		/* redirect type, gateway, + IP  */
770 	"Echo",
771 	"Time Exceeded",	/* transit, frag reassem + IP */
772 	"Parameter Problem",	/* pointer + IP */
773 	"Timestamp",		/* id + seq + three timestamps */
774 	"Timestamp Reply",	/* " */
775 	"Info Request",		/* id + sq */
776 	"Info Reply"		/* " */
777 };
778 #endif
779 
780 /*
781  * pr_icmph --
782  *	Print a descriptive string about an ICMP header.
783  */
784 pr_icmph(icp)
785 	struct icmp *icp;
786 {
787 	switch(icp->icmp_type) {
788 	case ICMP_ECHOREPLY:
789 		(void)printf("Echo Reply\n");
790 		/* XXX ID + Seq + Data */
791 		break;
792 	case ICMP_UNREACH:
793 		switch(icp->icmp_code) {
794 		case ICMP_UNREACH_NET:
795 			(void)printf("Destination Net Unreachable\n");
796 			break;
797 		case ICMP_UNREACH_HOST:
798 			(void)printf("Destination Host Unreachable\n");
799 			break;
800 		case ICMP_UNREACH_PROTOCOL:
801 			(void)printf("Destination Protocol Unreachable\n");
802 			break;
803 		case ICMP_UNREACH_PORT:
804 			(void)printf("Destination Port Unreachable\n");
805 			break;
806 		case ICMP_UNREACH_NEEDFRAG:
807 			(void)printf("frag needed and DF set\n");
808 			break;
809 		case ICMP_UNREACH_SRCFAIL:
810 			(void)printf("Source Route Failed\n");
811 			break;
812 		default:
813 			(void)printf("Dest Unreachable, Bad Code: %d\n",
814 			    icp->icmp_code);
815 			break;
816 		}
817 		/* Print returned IP header information */
818 #ifndef icmp_data
819 		pr_retip(&icp->icmp_ip);
820 #else
821 		pr_retip((struct ip *)icp->icmp_data);
822 #endif
823 		break;
824 	case ICMP_SOURCEQUENCH:
825 		(void)printf("Source Quench\n");
826 #ifndef icmp_data
827 		pr_retip(&icp->icmp_ip);
828 #else
829 		pr_retip((struct ip *)icp->icmp_data);
830 #endif
831 		break;
832 	case ICMP_REDIRECT:
833 		switch(icp->icmp_code) {
834 		case ICMP_REDIRECT_NET:
835 			(void)printf("Redirect Network");
836 			break;
837 		case ICMP_REDIRECT_HOST:
838 			(void)printf("Redirect Host");
839 			break;
840 		case ICMP_REDIRECT_TOSNET:
841 			(void)printf("Redirect Type of Service and Network");
842 			break;
843 		case ICMP_REDIRECT_TOSHOST:
844 			(void)printf("Redirect Type of Service and Host");
845 			break;
846 		default:
847 			(void)printf("Redirect, Bad Code: %d", icp->icmp_code);
848 			break;
849 		}
850 		(void)printf("(New addr: 0x%08lx)\n", icp->icmp_gwaddr.s_addr);
851 #ifndef icmp_data
852 		pr_retip(&icp->icmp_ip);
853 #else
854 		pr_retip((struct ip *)icp->icmp_data);
855 #endif
856 		break;
857 	case ICMP_ECHO:
858 		(void)printf("Echo Request\n");
859 		/* XXX ID + Seq + Data */
860 		break;
861 	case ICMP_TIMXCEED:
862 		switch(icp->icmp_code) {
863 		case ICMP_TIMXCEED_INTRANS:
864 			(void)printf("Time to live exceeded\n");
865 			break;
866 		case ICMP_TIMXCEED_REASS:
867 			(void)printf("Frag reassembly time exceeded\n");
868 			break;
869 		default:
870 			(void)printf("Time exceeded, Bad Code: %d\n",
871 			    icp->icmp_code);
872 			break;
873 		}
874 #ifndef icmp_data
875 		pr_retip(&icp->icmp_ip);
876 #else
877 		pr_retip((struct ip *)icp->icmp_data);
878 #endif
879 		break;
880 	case ICMP_PARAMPROB:
881 		(void)printf("Parameter problem: pointer = 0x%02x\n",
882 		    icp->icmp_hun.ih_pptr);
883 #ifndef icmp_data
884 		pr_retip(&icp->icmp_ip);
885 #else
886 		pr_retip((struct ip *)icp->icmp_data);
887 #endif
888 		break;
889 	case ICMP_TSTAMP:
890 		(void)printf("Timestamp\n");
891 		/* XXX ID + Seq + 3 timestamps */
892 		break;
893 	case ICMP_TSTAMPREPLY:
894 		(void)printf("Timestamp Reply\n");
895 		/* XXX ID + Seq + 3 timestamps */
896 		break;
897 	case ICMP_IREQ:
898 		(void)printf("Information Request\n");
899 		/* XXX ID + Seq */
900 		break;
901 	case ICMP_IREQREPLY:
902 		(void)printf("Information Reply\n");
903 		/* XXX ID + Seq */
904 		break;
905 #ifdef ICMP_MASKREQ
906 	case ICMP_MASKREQ:
907 		(void)printf("Address Mask Request\n");
908 		break;
909 #endif
910 #ifdef ICMP_MASKREPLY
911 	case ICMP_MASKREPLY:
912 		(void)printf("Address Mask Reply\n");
913 		break;
914 #endif
915 	default:
916 		(void)printf("Bad ICMP type: %d\n", icp->icmp_type);
917 	}
918 }
919 
920 /*
921  * pr_iph --
922  *	Print an IP header with options.
923  */
924 pr_iph(ip)
925 	struct ip *ip;
926 {
927 	int hlen;
928 	u_char *cp;
929 
930 	hlen = ip->ip_hl << 2;
931 	cp = (u_char *)ip + 20;		/* point to options */
932 
933 	(void)printf("Vr HL TOS  Len   ID Flg  off TTL Pro  cks      Src      Dst Data\n");
934 	(void)printf(" %1x  %1x  %02x %04x %04x",
935 	    ip->ip_v, ip->ip_hl, ip->ip_tos, ip->ip_len, ip->ip_id);
936 	(void)printf("   %1x %04x", ((ip->ip_off) & 0xe000) >> 13,
937 	    (ip->ip_off) & 0x1fff);
938 	(void)printf("  %02x  %02x %04x", ip->ip_ttl, ip->ip_p, ip->ip_sum);
939 	(void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_src.s_addr));
940 	(void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_dst.s_addr));
941 	/* dump and option bytes */
942 	while (hlen-- > 20) {
943 		(void)printf("%02x", *cp++);
944 	}
945 	(void)putchar('\n');
946 }
947 
948 /*
949  * pr_addr --
950  *	Return an ascii host address as a dotted quad and optionally with
951  * a hostname.
952  */
953 char *
954 pr_addr(l)
955 	u_long l;
956 {
957 	struct hostent *hp;
958 	static char buf[80];
959 
960 	if ((options & F_NUMERIC) ||
961 	    !(hp = gethostbyaddr((char *)&l, 4, AF_INET)))
962 		(void)sprintf(buf, "%s", inet_ntoa(*(struct in_addr *)&l));
963 	else
964 		(void)sprintf(buf, "%s (%s)", hp->h_name,
965 		    inet_ntoa(*(struct in_addr *)&l));
966 	return(buf);
967 }
968 
969 /*
970  * pr_retip --
971  *	Dump some info on a returned (via ICMP) IP packet.
972  */
973 pr_retip(ip)
974 	struct ip *ip;
975 {
976 	int hlen;
977 	u_char *cp;
978 
979 	pr_iph(ip);
980 	hlen = ip->ip_hl << 2;
981 	cp = (u_char *)ip + hlen;
982 
983 	if (ip->ip_p == 6)
984 		(void)printf("TCP: from port %u, to port %u (decimal)\n",
985 		    (*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3)));
986 	else if (ip->ip_p == 17)
987 		(void)printf("UDP: from port %u, to port %u (decimal)\n",
988 			(*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3)));
989 }
990 
991 fill(bp, patp)
992 	char *bp, *patp;
993 {
994 	register int ii, jj, kk;
995 	int pat[16];
996 	char *cp;
997 
998 	for (cp = patp; *cp; cp++)
999 		if (!isxdigit(*cp)) {
1000 			(void)fprintf(stderr,
1001 			    "ping: patterns must be specified as hex digits.\n");
1002 			exit(1);
1003 		}
1004 	ii = sscanf(patp,
1005 	    "%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x",
1006 	    &pat[0], &pat[1], &pat[2], &pat[3], &pat[4], &pat[5], &pat[6],
1007 	    &pat[7], &pat[8], &pat[9], &pat[10], &pat[11], &pat[12],
1008 	    &pat[13], &pat[14], &pat[15]);
1009 
1010 	if (ii > 0)
1011 		for (kk = 0;
1012 		    kk <= MAXPACKET - (8 + sizeof(struct timeval) + ii);
1013 		    kk += ii)
1014 			for (jj = 0; jj < ii; ++jj)
1015 				bp[jj + kk] = pat[jj];
1016 	if (!(options & F_QUIET)) {
1017 		(void)printf("PATTERN: 0x");
1018 		for (jj = 0; jj < ii; ++jj)
1019 			(void)printf("%02x", bp[jj] & 0xFF);
1020 		(void)printf("\n");
1021 	}
1022 }
1023 
1024 usage()
1025 {
1026 	(void)fprintf(stderr,
1027 	    "usage: ping [-Rdfnqrv] [-c count] [-i wait] [-l preload]\n\t[-p pattern] [-s packetsize] host\n");
1028 	exit(1);
1029 }
1030