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