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