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