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