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