xref: /netbsd-src/sbin/ping/ping.c (revision d909946ca08dceb44d7d0f22ec9488679695d976)
1 /*	$NetBSD: ping.c,v 1.111 2016/07/31 18:14:36 dholland Exp $	*/
2 
3 /*
4  * Copyright (c) 1989, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Mike Muuss.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 /*
36  *			P I N G . C
37  *
38  * Using the InterNet Control Message Protocol (ICMP) "ECHO" facility,
39  * measure round-trip-delays and packet loss across network paths.
40  *
41  * Author -
42  *	Mike Muuss
43  *	U. S. Army Ballistic Research Laboratory
44  *	December, 1983
45  * Modified at Uc Berkeley
46  * Record Route and verbose headers - Phil Dykstra, BRL, March 1988.
47  * Multicast options (ttl, if, loop) - Steve Deering, Stanford, August 1988.
48  * ttl, duplicate detection - Cliff Frost, UCB, April 1989
49  * Pad pattern - Cliff Frost (from Tom Ferrin, UCSF), April 1989
50  *
51  * Status -
52  *	Public Domain.  Distribution Unlimited.
53  *
54  * Bugs -
55  *	More statistics could always be gathered.
56  *	This program has to run SUID to ROOT to access the ICMP socket.
57  */
58 
59 #include <sys/cdefs.h>
60 #ifndef lint
61 __RCSID("$NetBSD: ping.c,v 1.111 2016/07/31 18:14:36 dholland Exp $");
62 #endif
63 
64 #include <stdio.h>
65 #include <stddef.h>
66 #include <errno.h>
67 #include <signal.h>
68 #include <sys/time.h>
69 #include <sys/types.h>
70 #include <sys/param.h>
71 #include <sys/socket.h>
72 #include <sys/file.h>
73 #include <termios.h>
74 #include <stdlib.h>
75 #include <unistd.h>
76 #include <poll.h>
77 #include <limits.h>
78 #include <math.h>
79 #include <string.h>
80 #include <err.h>
81 
82 #include <netinet/in_systm.h>
83 #include <netinet/in.h>
84 #include <netinet/ip.h>
85 #include <netinet/ip_icmp.h>
86 #include <netinet/ip_var.h>
87 #include <arpa/inet.h>
88 #include <ctype.h>
89 #include <netdb.h>
90 
91 #ifdef IPSEC
92 #include <netipsec/ipsec.h>
93 #endif /*IPSEC*/
94 
95 #include "prog_ops.h"
96 
97 #define FLOOD_INTVL	0.01		/* default flood output interval */
98 #define	MAXPACKET	(IP_MAXPACKET-60-8)	/* max packet size */
99 
100 #define F_VERBOSE	0x0001
101 #define F_QUIET		0x0002		/* minimize all output */
102 #define F_SEMI_QUIET	0x0004		/* ignore our ICMP errors */
103 #define F_FLOOD		0x0008		/* flood-ping */
104 #define	F_RECORD_ROUTE	0x0010		/* record route */
105 #define F_SOURCE_ROUTE	0x0020		/* loose source route */
106 #define F_PING_FILLED	0x0040		/* is buffer filled with user data? */
107 #define F_PING_RANDOM	0x0080		/* use random data */
108 #define	F_NUMERIC	0x0100		/* do not do gethostbyaddr() calls */
109 #define F_TIMING	0x0200		/* room for a timestamp */
110 #define F_DF		0x0400		/* set IP DF bit */
111 #define F_SOURCE_ADDR	0x0800		/* set source IP address/interface */
112 #define F_ONCE		0x1000		/* exit(0) after receiving 1 reply */
113 #define F_MCAST		0x2000		/* multicast target */
114 #define F_MCAST_NOLOOP	0x4000		/* no multicast loopback */
115 #define F_AUDIBLE	0x8000		/* audible output */
116 #define F_TIMING64	0x10000		/* 64 bit time, nanoseconds */
117 #ifdef IPSEC
118 #ifdef IPSEC_POLICY_IPSEC
119 #define F_POLICY	0x20000
120 #else
121 #define	F_AUTHHDR	0x20000
122 #define	F_ENCRYPT	0x40000
123 #endif /*IPSEC_POLICY_IPSEC*/
124 #endif /*IPSEC*/
125 
126 
127 /* MAX_DUP_CHK is the number of bits in received table, the
128  *	maximum number of received sequence numbers we can track to check
129  *	for duplicates.
130  */
131 #define MAX_DUP_CHK     (8 * 2048)
132 static u_char	rcvd_tbl[MAX_DUP_CHK/8];
133 static int     nrepeats = 0;
134 #define A(seq)	rcvd_tbl[(seq/8)%sizeof(rcvd_tbl)]  /* byte in array */
135 #define B(seq)	(1 << (seq & 0x07))	/* bit in byte */
136 #define SET(seq) (A(seq) |= B(seq))
137 #define CLR(seq) (A(seq) &= (~B(seq)))
138 #define TST(seq) (A(seq) & B(seq))
139 
140 struct tv32 {
141 	int32_t tv32_sec;
142 	int32_t tv32_usec;
143 };
144 
145 
146 static u_char	*packet;
147 static int	packlen;
148 static int	pingflags = 0, options;
149 static int	pongflags = 0;
150 static char	*fill_pat;
151 
152 static int s;					/* Socket file descriptor */
153 static int sloop;				/* Socket file descriptor/loopback */
154 
155 #define PHDR_LEN sizeof(struct tv32)		/* size of timestamp header */
156 #define PHDR64_LEN sizeof(struct timespec)	/* size of timestamp header */
157 static struct sockaddr_in whereto, send_addr;	/* Who to ping */
158 static struct sockaddr_in src_addr;		/* from where */
159 static struct sockaddr_in loc_addr;		/* 127.1 */
160 static int datalen;				/* How much data */
161 static int phdrlen;
162 
163 static sigset_t blockmask, enablemask;		/* signal masks */
164 
165 #ifndef __NetBSD__
166 static char *progname;
167 #define	getprogname()		(progname)
168 #define	setprogname(name)	((void)(progname = (name)))
169 #endif
170 
171 static char hostname[MAXHOSTNAMELEN];
172 
173 static struct {
174 	struct ip	o_ip;
175 	char		o_opt[MAX_IPOPTLEN];
176 	union {
177 		u_char	    u_buf[MAXPACKET+offsetof(struct icmp, icmp_data)];
178 		struct icmp u_icmp;
179 	} o_u;
180 } out_pack;
181 #define	opack_icmp	out_pack.o_u.u_icmp
182 static struct ip *opack_ip;
183 
184 static char optspace[MAX_IPOPTLEN];		/* record route space */
185 static int optlen;
186 
187 static int npackets;				/* total packets to send */
188 static int preload;				/* number of packets to "preload" */
189 static int ntransmitted;			/* output sequence # = #sent */
190 static int ident;				/* our ID, in network byte order */
191 
192 static int nreceived;				/* # of packets we got back */
193 
194 static double interval;			/* interval between packets */
195 static struct timespec interval_tv;
196 static double tmin = 999999999.0;
197 static double tmax = 0.0;
198 static double tsum = 0.0;			/* sum of all times */
199 static double tsumsq = 0.0;
200 static double maxwait = 0.0;
201 
202 static int bufspace = IP_MAXPACKET;
203 
204 static struct timespec now, clear_cache, last_tx, next_tx, first_tx;
205 static struct timespec last_rx, first_rx;
206 static int lastrcvd = 1;			/* last ping sent has been received */
207 
208 static struct timespec jiggle_time;
209 static int jiggle_cnt, total_jiggled, jiggle_direction = -1;
210 
211 __dead static void doit(void);
212 static void prefinish(int);
213 static void prtsig(int);
214 __dead static void finish(int);
215 static void blocksignals(void);
216 static void enablesignals(void);
217 static void summary(int);
218 static void pinger(void);
219 static void fill(void);
220 static void rnd_fill(void);
221 static double diffsec(struct timespec *, struct timespec *);
222 #if 0
223 static void timespecadd(struct timespec *, struct timespec *);
224 #endif
225 static void sec_to_timespec(const double, struct timespec *);
226 static double timespec_to_sec(const struct timespec *);
227 static void pr_pack(u_char *, int, struct sockaddr_in *);
228 static u_int16_t in_cksum(u_int16_t *, u_int);
229 static void pr_saddr(u_char *);
230 static char *pr_addr(struct in_addr *);
231 static void pr_iph(struct icmp *, int);
232 static void pr_retip(struct icmp *, int);
233 static int pr_icmph(struct icmp *, struct sockaddr_in *, int);
234 static void jiggle(int), jiggle_flush(int);
235 static void gethost(const char *, const char *,
236 		    struct sockaddr_in *, char *, int);
237 __dead static void usage(void);
238 
239 int
240 main(int argc, char *argv[])
241 {
242 	int c, i, on = 1, hostind = 0;
243 	long l;
244 	int len = -1, compat = 0;
245 	u_char ttl = 0;
246 	u_long tos = 0;
247 	char *p;
248 #ifdef IPSEC
249 #ifdef IPSEC_POLICY_IPSEC
250 	char *policy_in = NULL;
251 	char *policy_out = NULL;
252 #endif
253 #endif
254 #ifdef SIGINFO
255 	struct sigaction sa;
256 #endif
257 
258 	if (prog_init && prog_init() == -1)
259 		err(EXIT_FAILURE, "init failed");
260 
261 	if ((s = prog_socket(AF_INET, SOCK_RAW, IPPROTO_ICMP)) < 0)
262 		err(EXIT_FAILURE, "Cannot create socket");
263 	if ((sloop = prog_socket(AF_INET, SOCK_RAW, IPPROTO_ICMP)) < 0)
264 		err(EXIT_FAILURE, "Cannot create socket");
265 
266 	/*
267 	 * sloop is never read on.  This prevents packets from
268 	 * queueing in its recv buffer.
269 	 */
270 	if (prog_shutdown(sloop, SHUT_RD) == -1)
271 		warn("Cannot shutdown for read");
272 
273 	if (prog_setuid(prog_getuid()) == -1)
274 		err(EXIT_FAILURE, "setuid");
275 
276 	setprogname(argv[0]);
277 
278 #ifndef IPSEC
279 #define IPSECOPT
280 #else
281 #ifdef IPSEC_POLICY_IPSEC
282 #define IPSECOPT	"E:"
283 #else
284 #define IPSECOPT	"AE"
285 #endif /*IPSEC_POLICY_IPSEC*/
286 #endif
287 	while ((c = getopt(argc, argv,
288 			   "ac:CdDfg:h:i:I:l:Lnop:PqQrRs:t:T:vw:" IPSECOPT)) != -1) {
289 #undef IPSECOPT
290 		switch (c) {
291 		case 'a':
292 			pingflags |= F_AUDIBLE;
293 			break;
294 		case 'C':
295 			compat = 1;
296 			break;
297 		case 'c':
298 			npackets = strtol(optarg, &p, 0);
299 			if (*p != '\0' || npackets <= 0)
300 				errx(EXIT_FAILURE,
301 				    "Bad/invalid number of packets: %s",
302 				    optarg);
303 			break;
304 		case 'D':
305 			pingflags |= F_DF;
306 			break;
307 		case 'd':
308 			options |= SO_DEBUG;
309 			break;
310 		case 'f':
311 			pingflags |= F_FLOOD;
312 			break;
313 		case 'h':
314 			hostind = optind-1;
315 			break;
316 		case 'i':		/* wait between sending packets */
317 			interval = strtod(optarg, &p);
318 			if (*p != '\0' || interval <= 0)
319 				errx(EXIT_FAILURE, "Bad/invalid interval: %s",
320 				    optarg);
321 			break;
322 		case 'l':
323 			preload = strtol(optarg, &p, 0);
324 			if (*p != '\0' || preload < 0)
325 				errx(EXIT_FAILURE, "Bad/invalid preload value: "
326 				    "%s", optarg);
327 			break;
328 		case 'n':
329 			pingflags |= F_NUMERIC;
330 			break;
331 		case 'o':
332 			pingflags |= F_ONCE;
333 			break;
334 		case 'p':		/* fill buffer with user pattern */
335 			if (pingflags & F_PING_RANDOM)
336 				errx(EXIT_FAILURE,
337 				    "Only one of -P and -p allowed");
338 			pingflags |= F_PING_FILLED;
339 			fill_pat = optarg;
340 			break;
341 		case 'P':
342 			if (pingflags & F_PING_FILLED)
343 				errx(EXIT_FAILURE,
344 				    "Only one of -P and -p allowed");
345 			pingflags |= F_PING_RANDOM;
346 			break;
347 		case 'q':
348 			pingflags |= F_QUIET;
349 			break;
350 		case 'Q':
351 			pingflags |= F_SEMI_QUIET;
352 			break;
353 		case 'r':
354 			options |= SO_DONTROUTE;
355 			break;
356 		case 's':		/* size of packet to send */
357 			l = strtol(optarg, &p, 0);
358 			if (*p != '\0' || l < 0)
359 				errx(EXIT_FAILURE,
360 				    "Bad/invalid packet size: %s", optarg);
361 			if (l > MAXPACKET)
362 				errx(EXIT_FAILURE, "packet size is too large");
363 			len = (int)l;
364 			break;
365 		case 'v':
366 			pingflags |= F_VERBOSE;
367 			break;
368 		case 'R':
369 			pingflags |= F_RECORD_ROUTE;
370 			break;
371 		case 'L':
372 			pingflags |= F_MCAST_NOLOOP;
373 			break;
374 		case 't':
375 			tos = strtoul(optarg, &p, 0);
376 			if (*p != '\0' ||  tos > 0xFF)
377 				errx(EXIT_FAILURE, "bad tos value: %s", optarg);
378 			break;
379 		case 'T':
380 			l = strtol(optarg, &p, 0);
381 			if (*p != '\0' || l > 255 || l <= 0)
382 				errx(EXIT_FAILURE, "ttl out of range: %s",
383 				    optarg);
384 			ttl = (u_char)l;    /* cannot check >255 otherwise */
385 			break;
386 		case 'I':
387 			pingflags |= F_SOURCE_ADDR;
388 			gethost("-I", optarg, &src_addr, 0, 0);
389 			break;
390 		case 'g':
391 			pingflags |= F_SOURCE_ROUTE;
392 			gethost("-g", optarg, &send_addr, 0, 0);
393 			break;
394 		case 'w':
395 			maxwait = strtod(optarg, &p);
396 			if (*p != '\0' || maxwait <= 0)
397 				errx(EXIT_FAILURE, "Bad/invalid maxwait time: "
398 				    "%s", optarg);
399 			break;
400 #ifdef IPSEC
401 #ifdef IPSEC_POLICY_IPSEC
402 		case 'E':
403 			pingflags |= F_POLICY;
404 			if (!strncmp("in", optarg, 2)) {
405 				policy_in = strdup(optarg);
406 				if (!policy_in)
407 					err(EXIT_FAILURE, "strdup");
408 			} else if (!strncmp("out", optarg, 3)) {
409 				policy_out = strdup(optarg);
410 				if (!policy_out)
411 					err(EXIT_FAILURE, "strdup");
412 			} else
413 				errx(EXIT_FAILURE, "invalid security policy: "
414 				    "%s", optarg);
415 			break;
416 #else
417 		case 'A':
418 			pingflags |= F_AUTHHDR;
419 			break;
420 		case 'E':
421 			pingflags |= F_ENCRYPT;
422 			break;
423 #endif /*IPSEC_POLICY_IPSEC*/
424 #endif /*IPSEC*/
425 		default:
426 			usage();
427 			break;
428 		}
429 	}
430 
431 	if (interval == 0)
432 		interval = (pingflags & F_FLOOD) ? FLOOD_INTVL : 1.0;
433 #ifndef sgi
434 	if (pingflags & F_FLOOD && prog_getuid())
435 		errx(EXIT_FAILURE, "Must be superuser to use -f");
436 	if (interval < 1.0 && prog_getuid())
437 		errx(EXIT_FAILURE, "Must be superuser to use < 1 sec "
438 		    "ping interval");
439 	if (preload > 0 && prog_getuid())
440 		errx(EXIT_FAILURE, "Must be superuser to use -l");
441 #endif
442 	sec_to_timespec(interval, &interval_tv);
443 
444 	if ((pingflags & (F_AUDIBLE|F_FLOOD)) == (F_AUDIBLE|F_FLOOD))
445 		warnx("Sorry, no audible output for flood pings");
446 
447 	if (npackets != 0) {
448 		npackets += preload;
449 	} else {
450 		npackets = INT_MAX;
451 	}
452 
453 	if (hostind == 0) {
454 		if (optind != argc-1)
455 			usage();
456 		else
457 			hostind = optind;
458 	}
459 	else if (hostind >= argc - 1)
460 		usage();
461 
462 	gethost("", argv[hostind], &whereto, hostname, sizeof(hostname));
463 	if (IN_MULTICAST(ntohl(whereto.sin_addr.s_addr)))
464 		pingflags |= F_MCAST;
465 	if (!(pingflags & F_SOURCE_ROUTE))
466 		(void) memcpy(&send_addr, &whereto, sizeof(send_addr));
467 
468 	loc_addr.sin_family = AF_INET;
469 	loc_addr.sin_len = sizeof(struct sockaddr_in);
470 	loc_addr.sin_addr.s_addr = htonl((127 << 24) + 1);
471 
472 	if (len != -1)
473 		datalen = len;
474 	else
475 		datalen = 64 - PHDR_LEN;
476 	if (!compat && datalen >= (int)PHDR64_LEN) { /* can we time them? */
477 		pingflags |= F_TIMING64;
478 		phdrlen = PHDR64_LEN;
479 	} else if (datalen >= (int)PHDR_LEN) {	/* can we time them? */
480 		pingflags |= F_TIMING;
481 		phdrlen = PHDR_LEN;
482 	} else
483 		phdrlen = 0;
484 
485 	packlen = datalen + 60 + 76;	/* MAXIP + MAXICMP */
486 	if ((packet = malloc(packlen)) == NULL)
487 		err(EXIT_FAILURE, "Can't allocate %d bytes", packlen);
488 
489 	if (pingflags & F_PING_FILLED) {
490 		fill();
491 	} else if (pingflags & F_PING_RANDOM) {
492 		rnd_fill();
493 	} else {
494 		for (i = phdrlen; i < datalen; i++)
495 			opack_icmp.icmp_data[i] = i;
496 	}
497 
498 	ident = arc4random() & 0xFFFF;
499 
500 	if (options & SO_DEBUG) {
501 		if (prog_setsockopt(s, SOL_SOCKET, SO_DEBUG,
502 			       (char *)&on, sizeof(on)) == -1)
503 			warn("Can't turn on socket debugging");
504 	}
505 	if (options & SO_DONTROUTE) {
506 		if (prog_setsockopt(s, SOL_SOCKET, SO_DONTROUTE,
507 			       (char *)&on, sizeof(on)) == -1)
508 			warn("SO_DONTROUTE");
509 	}
510 
511 	if (options & SO_DEBUG) {
512 		if (prog_setsockopt(sloop, SOL_SOCKET, SO_DEBUG,
513 			       (char *)&on, sizeof(on)) == -1)
514 			warn("Can't turn on socket debugging");
515 	}
516 	if (options & SO_DONTROUTE) {
517 		if (prog_setsockopt(sloop, SOL_SOCKET, SO_DONTROUTE,
518 			       (char *)&on, sizeof(on)) == -1)
519 			warn("SO_DONTROUTE");
520 	}
521 
522 	if (pingflags & F_SOURCE_ROUTE) {
523 		optspace[IPOPT_OPTVAL] = IPOPT_LSRR;
524 		optspace[IPOPT_OLEN] = optlen = 7;
525 		optspace[IPOPT_OFFSET] = IPOPT_MINOFF;
526 		(void)memcpy(&optspace[IPOPT_MINOFF-1], &whereto.sin_addr,
527 			     sizeof(whereto.sin_addr));
528 		optspace[optlen++] = IPOPT_NOP;
529 	}
530 	if (pingflags & F_RECORD_ROUTE) {
531 		optspace[optlen+IPOPT_OPTVAL] = IPOPT_RR;
532 		optspace[optlen+IPOPT_OLEN] = (MAX_IPOPTLEN -1-optlen);
533 		optspace[optlen+IPOPT_OFFSET] = IPOPT_MINOFF;
534 		optlen = MAX_IPOPTLEN;
535 	}
536 	/* this leaves opack_ip 0(mod 4) aligned */
537 	opack_ip = (struct ip *)((char *)&out_pack.o_ip
538 				 + sizeof(out_pack.o_opt)
539 				 - optlen);
540 	(void) memcpy(opack_ip + 1, optspace, optlen);
541 
542 	if (prog_setsockopt(s, IPPROTO_IP, IP_HDRINCL,
543 	    (char *) &on, sizeof(on)) < 0)
544 		err(EXIT_FAILURE, "Can't set special IP header");
545 
546 	opack_ip->ip_v = IPVERSION;
547 	opack_ip->ip_hl = (sizeof(struct ip)+optlen) >> 2;
548 	opack_ip->ip_tos = tos;
549 	opack_ip->ip_off = (pingflags & F_DF) ? IP_DF : 0;
550 	opack_ip->ip_ttl = ttl ? ttl : MAXTTL;
551 	opack_ip->ip_p = IPPROTO_ICMP;
552 	opack_ip->ip_src = src_addr.sin_addr;
553 	opack_ip->ip_dst = send_addr.sin_addr;
554 
555 	if (pingflags & F_MCAST) {
556 		if (pingflags & F_MCAST_NOLOOP) {
557 			u_char loop = 0;
558 			if (prog_setsockopt(s, IPPROTO_IP,
559 			    IP_MULTICAST_LOOP,
560 			    (char *) &loop, 1) < 0)
561 				err(EXIT_FAILURE, "Can't disable multicast loopback");
562 		}
563 
564 		if (ttl != 0
565 		    && prog_setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL,
566 		    (char *) &ttl, 1) < 0)
567 			err(EXIT_FAILURE, "Can't set multicast time-to-live");
568 
569 		if ((pingflags & F_SOURCE_ADDR)
570 		    && prog_setsockopt(s, IPPROTO_IP, IP_MULTICAST_IF,
571 				  (char *) &src_addr.sin_addr,
572 				  sizeof(src_addr.sin_addr)) < 0)
573 			err(EXIT_FAILURE, "Can't set multicast source interface");
574 
575 	} else if (pingflags & F_SOURCE_ADDR) {
576 		if (prog_setsockopt(s, IPPROTO_IP, IP_MULTICAST_IF,
577 			       (char *) &src_addr.sin_addr,
578 			       sizeof(src_addr.sin_addr)) < 0)
579 			err(EXIT_FAILURE, "Can't set source interface/address");
580 	}
581 #ifdef IPSEC
582 #ifdef IPSEC_POLICY_IPSEC
583     {
584 	char *buf;
585 	if (pingflags & F_POLICY) {
586 		if (policy_in != NULL) {
587 			buf = ipsec_set_policy(policy_in, strlen(policy_in));
588 			if (buf == NULL)
589 				errx(EXIT_FAILURE, "%s", ipsec_strerror());
590 			if (prog_setsockopt(s, IPPROTO_IP, IP_IPSEC_POLICY,
591 					buf, ipsec_get_policylen(buf)) < 0) {
592 				err(EXIT_FAILURE, "ipsec policy cannot be "
593 				    "configured");
594 			}
595 			free(buf);
596 		}
597 		if (policy_out != NULL) {
598 			buf = ipsec_set_policy(policy_out, strlen(policy_out));
599 			if (buf == NULL)
600 				errx(EXIT_FAILURE, "%s", ipsec_strerror());
601 			if (prog_setsockopt(s, IPPROTO_IP, IP_IPSEC_POLICY,
602 					buf, ipsec_get_policylen(buf)) < 0) {
603 				err(EXIT_FAILURE, "ipsec policy cannot be "
604 				    "configured");
605 			}
606 			free(buf);
607 		}
608 	}
609 	buf = ipsec_set_policy("out bypass", strlen("out bypass"));
610 	if (buf == NULL)
611 		errx(EXIT_FAILURE, "%s", ipsec_strerror());
612 	if (prog_setsockopt(sloop, IPPROTO_IP, IP_IPSEC_POLICY,
613 			buf, ipsec_get_policylen(buf)) < 0) {
614 #if 0
615 		warnx("ipsec is not configured");
616 #else
617 		/* ignore it, should be okay */
618 #endif
619 	}
620 	free(buf);
621     }
622 #else
623     {
624 	int optval;
625 	if (pingflags & F_AUTHHDR) {
626 		optval = IPSEC_LEVEL_REQUIRE;
627 #ifdef IP_AUTH_TRANS_LEVEL
628 		(void)prog_setsockopt(s, IPPROTO_IP, IP_AUTH_TRANS_LEVEL,
629 			(char *)&optval, sizeof(optval));
630 #else
631 		(void)prog_setsockopt(s, IPPROTO_IP, IP_AUTH_LEVEL,
632 			(char *)&optval, sizeof(optval));
633 #endif
634 	}
635 	if (pingflags & F_ENCRYPT) {
636 		optval = IPSEC_LEVEL_REQUIRE;
637 		(void)prog_setsockopt(s, IPPROTO_IP, IP_ESP_TRANS_LEVEL,
638 			(char *)&optval, sizeof(optval));
639 	}
640 	optval = IPSEC_LEVEL_BYPASS;
641 #ifdef IP_AUTH_TRANS_LEVEL
642 	(void)prog_setsockopt(sloop, IPPROTO_IP, IP_AUTH_TRANS_LEVEL,
643 		(char *)&optval, sizeof(optval));
644 #else
645 	(void)prog_setsockopt(sloop, IPPROTO_IP, IP_AUTH_LEVEL,
646 		(char *)&optval, sizeof(optval));
647 #endif
648 	(void)prog_setsockopt(sloop, IPPROTO_IP, IP_ESP_TRANS_LEVEL,
649 		(char *)&optval, sizeof(optval));
650     }
651 #endif /*IPSEC_POLICY_IPSEC*/
652 #endif /*IPSEC*/
653 
654 	(void)printf("PING %s (%s): %d data bytes\n", hostname,
655 		     inet_ntoa(whereto.sin_addr), datalen);
656 
657 	/* When pinging the broadcast address, you can get a lot
658 	 * of answers.  Doing something so evil is useful if you
659 	 * are trying to stress the ethernet, or just want to
660 	 * fill the arp cache to get some stuff for /etc/ethers.
661 	 */
662 	while (0 > prog_setsockopt(s, SOL_SOCKET, SO_RCVBUF,
663 			      (char*)&bufspace, sizeof(bufspace))) {
664 		if ((bufspace -= 4096) <= 0)
665 			err(EXIT_FAILURE, "Cannot set the receive buffer size");
666 	}
667 
668 	/* make it possible to send giant probes, but do not worry now
669 	 * if it fails, since we probably won't send giant probes.
670 	 */
671 	(void)prog_setsockopt(s, SOL_SOCKET, SO_SNDBUF,
672 			 (char*)&bufspace, sizeof(bufspace));
673 
674 	(void)signal(SIGINT, prefinish);
675 
676 	/*
677 	 * Set up two signal masks:
678 	 *    - blockmask blocks the signals we catch
679 	 *    - enablemask does not
680 	 */
681 
682 	sigemptyset(&enablemask);
683 	sigemptyset(&blockmask);
684 	sigaddset(&blockmask, SIGINT);
685 #ifdef SIGINFO
686 	sigaddset(&blockmask, SIGINFO);
687 #else
688 	sigaddset(&blockmask, SIGQUIT);
689 #endif
690 
691 #ifdef SIGINFO
692 	sa.sa_handler = prtsig;
693 	sa.sa_flags = SA_NOKERNINFO;
694 	sigemptyset(&sa.sa_mask);
695 	(void)sigaction(SIGINFO, &sa, NULL);
696 #else
697 	(void)signal(SIGQUIT, prtsig);
698 #endif
699 	(void)signal(SIGCONT, prtsig);
700 
701 	blocksignals();
702 
703 	/* fire off them quickies */
704 	for (i = 0; i < preload; i++) {
705 		clock_gettime(CLOCK_MONOTONIC, &now);
706 		pinger();
707 	}
708 
709 	doit();
710 	return 0;
711 }
712 
713 static void
714 doit(void)
715 {
716 	int cc;
717 	struct sockaddr_in from;
718 	socklen_t fromlen;
719 	double sec, last, d_last;
720 	struct pollfd fdmaskp[1];
721 
722 	(void)clock_gettime(CLOCK_MONOTONIC, &clear_cache);
723 	if (maxwait != 0) {
724 		last = timespec_to_sec(&clear_cache) + maxwait;
725 		d_last = 0;
726 	} else {
727 		last = 0;
728 		d_last = 365*24*60*60;
729 	}
730 
731 	do {
732 		clock_gettime(CLOCK_MONOTONIC, &now);
733 
734 		if (last != 0)
735 			d_last = last - timespec_to_sec(&now);
736 
737 		if (ntransmitted < npackets && d_last > 0) {
738 			/* send if within 100 usec or late for next packet */
739 			sec = diffsec(&next_tx, &now);
740 			if (sec <= 0.0001 ||
741 			    (lastrcvd && (pingflags & F_FLOOD))) {
742 				pinger();
743 				sec = diffsec(&next_tx, &now);
744 			}
745 			if (sec < 0.0)
746 				sec = 0.0;
747 			if (d_last < sec)
748 				sec = d_last;
749 
750 		} else {
751 			/* For the last response, wait twice as long as the
752 			 * worst case seen, or 10 times as long as the
753 			 * maximum interpacket interval, whichever is longer.
754 			 */
755 			sec = MAX(2 * tmax, 10 * interval) -
756 			    diffsec(&now, &last_tx);
757 			if (d_last < sec)
758 				sec = d_last;
759 			if (sec <= 0)
760 				break;
761 		}
762 
763 
764 		fdmaskp[0].fd = s;
765 		fdmaskp[0].events = POLLIN;
766 
767 		enablesignals();
768 		cc = prog_poll(fdmaskp, 1, (int)(sec * 1000));
769 		blocksignals();
770 
771 		if (cc <= 0) {
772 			if (cc < 0) {
773 				if (errno == EINTR)
774 					continue;
775 				jiggle_flush(1);
776 				err(EXIT_FAILURE, "poll");
777 			}
778 			continue;
779 		}
780 
781 		fromlen  = sizeof(from);
782 		cc = prog_recvfrom(s, (char *) packet, packlen,
783 			      0, (struct sockaddr *)&from,
784 			      &fromlen);
785 		if (cc < 0) {
786 			if (errno != EINTR) {
787 				jiggle_flush(1);
788 				warn("recvfrom");
789 				(void)fflush(stderr);
790 			}
791 			continue;
792 		}
793 		clock_gettime(CLOCK_MONOTONIC, &now);
794 		pr_pack(packet, cc, &from);
795 
796 	} while (nreceived < npackets
797 		 && (nreceived == 0 || !(pingflags & F_ONCE)));
798 
799 	finish(0);
800 }
801 
802 
803 static void
804 jiggle_flush(int nl)			/* new line if there are dots */
805 {
806 	int serrno = errno;
807 
808 	if (jiggle_cnt > 0) {
809 		total_jiggled += jiggle_cnt;
810 		jiggle_direction = 1;
811 		do {
812 			(void)putchar('.');
813 		} while (--jiggle_cnt > 0);
814 
815 	} else if (jiggle_cnt < 0) {
816 		total_jiggled -= jiggle_cnt;
817 		jiggle_direction = -1;
818 		do {
819 			(void)putchar('\b');
820 		} while (++jiggle_cnt < 0);
821 	}
822 
823 	if (nl) {
824 		if (total_jiggled != 0)
825 			(void)putchar('\n');
826 		total_jiggled = 0;
827 		jiggle_direction = -1;
828 	}
829 
830 	(void)fflush(stdout);
831 	(void)fflush(stderr);
832 	jiggle_time = now;
833 	errno = serrno;
834 }
835 
836 
837 /* jiggle the cursor for flood-ping
838  */
839 static void
840 jiggle(int delta)
841 {
842 	double dt;
843 
844 	if (pingflags & F_QUIET)
845 		return;
846 
847 	/* do not back up into messages */
848 	if (total_jiggled+jiggle_cnt+delta < 0)
849 		return;
850 
851 	jiggle_cnt += delta;
852 
853 	/* flush the FLOOD dots when things are quiet
854 	 * or occassionally to make the cursor jiggle.
855 	 */
856 	dt = diffsec(&last_tx, &jiggle_time);
857 	if (dt > 0.2 || (dt >= 0.15 && delta*jiggle_direction < 0))
858 		jiggle_flush(0);
859 }
860 
861 
862 /*
863  * Compose and transmit an ICMP ECHO REQUEST packet.  The IP packet
864  * will be added on by the kernel.  The ID field is our UNIX process ID,
865  * and the sequence number is an ascending integer.  The first phdrlen bytes
866  * of the data portion are used to hold a UNIX "timeval" struct in VAX
867  * byte-order, to compute the round-trip time, or a UNIX "timespec" in native
868  * format.
869  */
870 static void
871 pinger(void)
872 {
873 	struct tv32 tv32;
874 	int i, cc, sw;
875 
876 	opack_icmp.icmp_code = 0;
877 	opack_icmp.icmp_seq = htons((u_int16_t)(ntransmitted));
878 
879 	/* clear the cached route in the kernel after an ICMP
880 	 * response such as a Redirect is seen to stop causing
881 	 * more such packets.  Also clear the cached route
882 	 * periodically in case of routing changes that make
883 	 * black holes come and go.
884 	 */
885 	if (clear_cache.tv_sec != now.tv_sec) {
886 		opack_icmp.icmp_type = ICMP_ECHOREPLY;
887 		opack_icmp.icmp_id = ~ident;
888 		opack_icmp.icmp_cksum = 0;
889 		opack_icmp.icmp_cksum = in_cksum((u_int16_t *)&opack_icmp,
890 		    phdrlen);
891 		sw = 0;
892 		if (prog_setsockopt(sloop, IPPROTO_IP, IP_HDRINCL,
893 			       (char *)&sw, sizeof(sw)) < 0)
894 			err(EXIT_FAILURE, "Can't turn off special IP header");
895 		if (prog_sendto(sloop, (char *) &opack_icmp,
896 			   ICMP_MINLEN, MSG_DONTROUTE,
897 			   (struct sockaddr *)&loc_addr,
898 			   sizeof(struct sockaddr_in)) < 0) {
899 			/*
900 			 * XXX: we only report this as a warning in verbose
901 			 * mode because people get confused when they see
902 			 * this error when they are running in single user
903 			 * mode and they have not configured lo0
904 			 */
905 			if (pingflags & F_VERBOSE)
906 				warn("failed to clear cached route");
907 		}
908 		sw = 1;
909 		if (prog_setsockopt(sloop, IPPROTO_IP, IP_HDRINCL,
910 			       (char *)&sw, sizeof(sw)) < 0)
911 			err(EXIT_FAILURE, "Can't set special IP header");
912 
913 		(void)clock_gettime(CLOCK_MONOTONIC, &clear_cache);
914 	}
915 
916 	opack_icmp.icmp_type = ICMP_ECHO;
917 	opack_icmp.icmp_id = ident;
918 
919 	if (pingflags & F_TIMING) {
920 		tv32.tv32_sec = (uint32_t)htonl(now.tv_sec);
921 		tv32.tv32_usec = htonl(now.tv_nsec / 1000);
922 		(void) memcpy(&opack_icmp.icmp_data[0], &tv32, sizeof(tv32));
923 	} else if (pingflags & F_TIMING64)
924 		(void) memcpy(&opack_icmp.icmp_data[0], &now, sizeof(now));
925 
926 	cc = MAX(datalen, ICMP_MINLEN) + PHDR_LEN;
927 	opack_icmp.icmp_cksum = 0;
928 	opack_icmp.icmp_cksum = in_cksum((u_int16_t *)&opack_icmp, cc);
929 
930 	cc += opack_ip->ip_hl<<2;
931 	opack_ip->ip_len = cc;
932 	i = prog_sendto(s, (char *) opack_ip, cc, 0,
933 		   (struct sockaddr *)&send_addr, sizeof(struct sockaddr_in));
934 	if (i != cc) {
935 		jiggle_flush(1);
936 		if (i < 0)
937 			warn("sendto");
938 		else
939 			warnx("wrote %s %d chars, ret=%d", hostname, cc, i);
940 		(void)fflush(stderr);
941 	}
942 	lastrcvd = 0;
943 
944 	CLR(ntransmitted);
945 	ntransmitted++;
946 
947 	last_tx = now;
948 	if (next_tx.tv_sec == 0) {
949 		first_tx = now;
950 		next_tx = now;
951 	}
952 
953 	/* Transmit regularly, at always the same microsecond in the
954 	 * second when going at one packet per second.
955 	 * If we are at most 100 ms behind, send extras to get caught up.
956 	 * Otherwise, skip packets we were too slow to send.
957 	 */
958 	if (diffsec(&next_tx, &now) <= interval) {
959 		do {
960 			timespecadd(&next_tx, &interval_tv, &next_tx);
961 		} while (diffsec(&next_tx, &now) < -0.1);
962 	}
963 
964 	if (pingflags & F_FLOOD)
965 		jiggle(1);
966 
967 	/* While the packet is going out, ready buffer for the next
968 	 * packet. Use a fast but not very good random number generator.
969 	 */
970 	if (pingflags & F_PING_RANDOM)
971 		rnd_fill();
972 }
973 
974 
975 static void
976 pr_pack_sub(int cc,
977 	    char *addr,
978 	    int seqno,
979 	    int dupflag,
980 	    int ttl,
981 	    double triptime)
982 {
983 	jiggle_flush(1);
984 
985 	if (pingflags & F_FLOOD)
986 		return;
987 
988 	(void)printf("%d bytes from %s: icmp_seq=%u", cc, addr, seqno);
989 	if (dupflag)
990 		(void)printf(" DUP!");
991 	(void)printf(" ttl=%d", ttl);
992 	if (pingflags & (F_TIMING|F_TIMING64)) {
993 		const unsigned int prec = (pingflags & F_TIMING64) != 0 ? 6 : 3;
994 
995 		(void)printf(" time=%.*f ms", prec, triptime*1000.0);
996 	}
997 
998 	/*
999 	 * Send beep to stderr, since that's more likely than stdout
1000 	 * to go to a terminal..
1001 	 */
1002 	if (pingflags & F_AUDIBLE && !dupflag)
1003 		(void)fprintf(stderr,"\a");
1004 }
1005 
1006 
1007 /*
1008  * Print out the packet, if it came from us.  This logic is necessary
1009  * because ALL readers of the ICMP socket get a copy of ALL ICMP packets
1010  * which arrive ('tis only fair).  This permits multiple copies of this
1011  * program to be run without having intermingled output (or statistics!).
1012  */
1013 static void
1014 pr_pack(u_char *buf,
1015 	int tot_len,
1016 	struct sockaddr_in *from)
1017 {
1018 	struct ip *ip;
1019 	struct icmp *icp;
1020 	int i, j, net_len;
1021 	u_char *cp;
1022 	static int old_rrlen;
1023 	static char old_rr[MAX_IPOPTLEN];
1024 	int hlen, dupflag = 0, dumped;
1025 	double triptime = 0.0;
1026 #define PR_PACK_SUB() {if (!dumped) {			\
1027 	dumped = 1;					\
1028 	pr_pack_sub(net_len, inet_ntoa(from->sin_addr),	\
1029 		    ntohs((u_int16_t)icp->icmp_seq),	\
1030 		    dupflag, ip->ip_ttl, triptime);}}
1031 
1032 	/* Check the IP header */
1033 	ip = (struct ip *) buf;
1034 	hlen = ip->ip_hl << 2;
1035 	if (tot_len < hlen + ICMP_MINLEN) {
1036 		if (pingflags & F_VERBOSE) {
1037 			jiggle_flush(1);
1038 			(void)printf("packet too short (%d bytes) from %s\n",
1039 				     tot_len, inet_ntoa(from->sin_addr));
1040 		}
1041 		return;
1042 	}
1043 
1044 	/* Now the ICMP part */
1045 	dumped = 0;
1046 	net_len = tot_len - hlen;
1047 	icp = (struct icmp *)(buf + hlen);
1048 	if (icp->icmp_type == ICMP_ECHOREPLY
1049 	    && icp->icmp_id == ident) {
1050 
1051 		if (icp->icmp_seq == htons((u_int16_t)(ntransmitted-1)))
1052 			lastrcvd = 1;
1053 		last_rx = now;
1054 		if (first_rx.tv_sec == 0)
1055 			first_rx = last_rx;
1056 		nreceived++;
1057 		if (pingflags & (F_TIMING|F_TIMING64)) {
1058 			struct timespec tv;
1059 
1060 			if (pingflags & F_TIMING) {
1061 				struct tv32 tv32;
1062 
1063 				(void)memcpy(&tv32, icp->icmp_data, sizeof(tv32));
1064 				tv.tv_sec = (uint32_t)ntohl(tv32.tv32_sec);
1065 				tv.tv_nsec = ntohl(tv32.tv32_usec) * 1000;
1066 			} else if (pingflags & F_TIMING64)
1067 				(void)memcpy(&tv, icp->icmp_data, sizeof(tv));
1068 			else
1069 				memset(&tv, 0, sizeof(tv));	/* XXX: gcc */
1070 
1071 			triptime = diffsec(&last_rx, &tv);
1072 			tsum += triptime;
1073 			tsumsq += triptime * triptime;
1074 			if (triptime < tmin)
1075 				tmin = triptime;
1076 			if (triptime > tmax)
1077 				tmax = triptime;
1078 		}
1079 
1080 		if (TST(ntohs((u_int16_t)icp->icmp_seq))) {
1081 			nrepeats++, nreceived--;
1082 			dupflag=1;
1083 		} else {
1084 			SET(ntohs((u_int16_t)icp->icmp_seq));
1085 		}
1086 
1087 		if (tot_len != opack_ip->ip_len) {
1088 			PR_PACK_SUB();
1089 			switch (opack_ip->ip_len - tot_len) {
1090 			case MAX_IPOPTLEN:
1091 				if ((pongflags & F_RECORD_ROUTE) != 0)
1092 					break;
1093 				if ((pingflags & F_RECORD_ROUTE) == 0)
1094 					goto out;
1095 				pongflags |= F_RECORD_ROUTE;
1096 				(void)printf("\nremote host does not "
1097 				    "support record route");
1098 				break;
1099 			case 8:
1100 				if ((pongflags & F_SOURCE_ROUTE) != 0)
1101 					break;
1102 				if ((pingflags & F_SOURCE_ROUTE) == 0)
1103 					goto out;
1104 				pongflags |= F_SOURCE_ROUTE;
1105 				(void)printf("\nremote host does not "
1106 				    "support source route");
1107 				break;
1108 			default:
1109 			out:
1110 				(void)printf("\nwrong total length %d "
1111 				    "instead of %d", tot_len, opack_ip->ip_len);
1112 				break;
1113 			}
1114 		}
1115 
1116 		if (!dupflag) {
1117 			static u_int16_t last_seqno = 0xffff;
1118 			u_int16_t seqno = ntohs((u_int16_t)icp->icmp_seq);
1119 			u_int16_t gap = seqno - (last_seqno + 1);
1120 			if (gap > 0 && gap < 0x8000 &&
1121 			    (pingflags & F_VERBOSE)) {
1122 				(void)printf("[*** sequence gap of %u "
1123 				    "packets from %u ... %u ***]\n", gap,
1124 				    (u_int16_t) (last_seqno + 1),
1125 				    (u_int16_t) (seqno - 1));
1126 				if (pingflags & F_QUIET)
1127 					summary(0);
1128 			}
1129 
1130 			if (gap < 0x8000)
1131 				last_seqno = seqno;
1132 		}
1133 
1134 		if (pingflags & F_QUIET)
1135 			return;
1136 
1137 		if (!(pingflags & F_FLOOD))
1138 			PR_PACK_SUB();
1139 
1140 		/* check the data */
1141 		if ((size_t)(tot_len - hlen) >
1142 		    offsetof(struct icmp, icmp_data) + datalen
1143 		    && !(pingflags & F_PING_RANDOM)
1144 		    && memcmp(icp->icmp_data + phdrlen,
1145 			    opack_icmp.icmp_data + phdrlen,
1146 			    datalen - phdrlen)) {
1147 			for (i = phdrlen; i < datalen; i++) {
1148 				if (icp->icmp_data[i] !=
1149 				    opack_icmp.icmp_data[i])
1150 					break;
1151 			}
1152 			PR_PACK_SUB();
1153 			(void)printf("\nwrong data byte #%d should have been"
1154 				     " %#x but was %#x", i - phdrlen,
1155 				     (u_char)opack_icmp.icmp_data[i],
1156 				     (u_char)icp->icmp_data[i]);
1157 			for (i = phdrlen; i < datalen; i++) {
1158 				if ((i % 16) == 0)
1159 					(void)printf("\n\t");
1160 				(void)printf("%2x ",(u_char)icp->icmp_data[i]);
1161 			}
1162 		}
1163 
1164 	} else {
1165 		if (!pr_icmph(icp, from, net_len))
1166 			return;
1167 		dumped = 2;
1168 	}
1169 
1170 	/* Display any IP options */
1171 	cp = buf + sizeof(struct ip);
1172 	while (hlen > (int)sizeof(struct ip)) {
1173 		switch (*cp) {
1174 		case IPOPT_EOL:
1175 			hlen = 0;
1176 			break;
1177 		case IPOPT_LSRR:
1178 			hlen -= 2;
1179 			j = *++cp;
1180 			++cp;
1181 			j -= IPOPT_MINOFF;
1182 			if (j <= 0)
1183 				continue;
1184 			if (dumped <= 1) {
1185 				j = ((j+3)/4)*4;
1186 				hlen -= j;
1187 				cp += j;
1188 				break;
1189 			}
1190 			PR_PACK_SUB();
1191 			(void)printf("\nLSRR: ");
1192 			for (;;) {
1193 				pr_saddr(cp);
1194 				cp += 4;
1195 				hlen -= 4;
1196 				j -= 4;
1197 				if (j <= 0)
1198 					break;
1199 				(void)putchar('\n');
1200 			}
1201 			break;
1202 		case IPOPT_RR:
1203 			j = *++cp;	/* get length */
1204 			i = *++cp;	/* and pointer */
1205 			hlen -= 2;
1206 			if (i > j)
1207 				i = j;
1208 			i -= IPOPT_MINOFF;
1209 			if (i <= 0)
1210 				continue;
1211 			if (dumped <= 1) {
1212 				if (i == old_rrlen
1213 				    && !memcmp(cp, old_rr, i)) {
1214 					if (dumped)
1215 					    (void)printf("\t(same route)");
1216 					j = ((i+3)/4)*4;
1217 					hlen -= j;
1218 					cp += j;
1219 					break;
1220 				}
1221 				old_rrlen = i;
1222 				(void) memcpy(old_rr, cp, i);
1223 			}
1224 			if (!dumped) {
1225 				jiggle_flush(1);
1226 				(void)printf("RR: ");
1227 				dumped = 1;
1228 			} else {
1229 				(void)printf("\nRR: ");
1230 			}
1231 			for (;;) {
1232 				pr_saddr(cp);
1233 				cp += 4;
1234 				hlen -= 4;
1235 				i -= 4;
1236 				if (i <= 0)
1237 					break;
1238 				(void)putchar('\n');
1239 			}
1240 			break;
1241 		case IPOPT_NOP:
1242 			if (dumped <= 1)
1243 				break;
1244 			PR_PACK_SUB();
1245 			(void)printf("\nNOP");
1246 			break;
1247 #ifdef sgi
1248 		case IPOPT_SECURITY:	/* RFC 1108 RIPSO BSO */
1249 		case IPOPT_ESO:		/* RFC 1108 RIPSO ESO */
1250 		case IPOPT_CIPSO:	/* Commercial IPSO */
1251 			if ((sysconf(_SC_IP_SECOPTS)) > 0) {
1252 				i = (unsigned)cp[1];
1253 				hlen -= i - 1;
1254 				PR_PACK_SUB();
1255 				(void)printf("\nSEC:");
1256 				while (i--) {
1257 					(void)printf(" %02x", *cp++);
1258 				}
1259 				cp--;
1260 				break;
1261 			}
1262 #endif
1263 		default:
1264 			PR_PACK_SUB();
1265 			(void)printf("\nunknown option 0x%x", *cp);
1266 			break;
1267 		}
1268 		hlen--;
1269 		cp++;
1270 	}
1271 
1272 	if (dumped) {
1273 		(void)putchar('\n');
1274 		(void)fflush(stdout);
1275 	} else {
1276 		jiggle(-1);
1277 	}
1278 }
1279 
1280 
1281 /* Compute the IP checksum
1282  *	This assumes the packet is less than 32K long.
1283  */
1284 static u_int16_t
1285 in_cksum(u_int16_t *p, u_int len)
1286 {
1287 	u_int32_t sum = 0;
1288 	int nwords = len >> 1;
1289 
1290 	while (nwords-- != 0)
1291 		sum += *p++;
1292 
1293 	if (len & 1) {
1294 		union {
1295 			u_int16_t w;
1296 			u_int8_t c[2];
1297 		} u;
1298 		u.c[0] = *(u_char *)p;
1299 		u.c[1] = 0;
1300 		sum += u.w;
1301 	}
1302 
1303 	/* end-around-carry */
1304 	sum = (sum >> 16) + (sum & 0xffff);
1305 	sum += (sum >> 16);
1306 	return (~sum);
1307 }
1308 
1309 
1310 /*
1311  * compute the difference of two timespecs in seconds
1312  */
1313 static double
1314 diffsec(struct timespec *timenow,
1315 	struct timespec *then)
1316 {
1317 	if (timenow->tv_sec == 0)
1318 		return -1;
1319 	return (timenow->tv_sec - then->tv_sec)
1320 	    * 1.0 + (timenow->tv_nsec - then->tv_nsec) / 1000000000.0;
1321 }
1322 
1323 
1324 #if 0
1325 static void
1326 timespecadd(struct timespec *t1,
1327 	   struct timespec *t2)
1328 {
1329 
1330 	t1->tv_sec += t2->tv_sec;
1331 	if ((t1->tv_nsec += t2->tv_nsec) >= 1000000000) {
1332 		t1->tv_sec++;
1333 		t1->tv_nsec -= 1000000000;
1334 	}
1335 }
1336 #endif
1337 
1338 
1339 static void
1340 sec_to_timespec(const double sec, struct timespec *tp)
1341 {
1342 	tp->tv_sec = sec;
1343 	tp->tv_nsec = (sec - tp->tv_sec) * 1000000000.0;
1344 }
1345 
1346 
1347 static double
1348 timespec_to_sec(const struct timespec *tp)
1349 {
1350 	return tp->tv_sec + tp->tv_nsec / 1000000000.0;
1351 }
1352 
1353 
1354 /*
1355  * Print statistics.
1356  * Heavily buffered STDIO is used here, so that all the statistics
1357  * will be written with 1 sys-write call.  This is nice when more
1358  * than one copy of the program is running on a terminal;  it prevents
1359  * the statistics output from becomming intermingled.
1360  */
1361 static void
1362 summary(int header)
1363 {
1364 	jiggle_flush(1);
1365 
1366 	if (header)
1367 		(void)printf("\n----%s PING Statistics----\n", hostname);
1368 	(void)printf("%d packets transmitted, ", ntransmitted);
1369 	(void)printf("%d packets received, ", nreceived);
1370 	if (nrepeats)
1371 		(void)printf("+%d duplicates, ", nrepeats);
1372 	if (ntransmitted) {
1373 		if (nreceived > ntransmitted)
1374 			(void)printf("-- somebody's duplicating packets!");
1375 		else
1376 			(void)printf("%.1f%% packet loss",
1377 				     (((ntransmitted-nreceived)*100.0) /
1378 					    ntransmitted));
1379 	}
1380 	(void)printf("\n");
1381 	if (nreceived && (pingflags & (F_TIMING|F_TIMING64))) {
1382 		double n = nreceived + nrepeats;
1383 		double avg = (tsum / n);
1384 		double variance = 0.0;
1385 		const unsigned int prec = (pingflags & F_TIMING64) != 0 ? 6 : 3;
1386 		if (n>1)
1387 			variance = (tsumsq - n*avg*avg) /(n-1);
1388 
1389 		(void)printf("round-trip min/avg/max/stddev = "
1390 			"%.*f/%.*f/%.*f/%.*f ms\n",
1391 			prec, tmin * 1000.0,
1392 			prec, avg * 1000.0,
1393 			prec, tmax * 1000.0,
1394 			prec, sqrt(variance) * 1000.0);
1395 		if (pingflags & F_FLOOD) {
1396 			double r = diffsec(&last_rx, &first_rx);
1397 			double t = diffsec(&last_tx, &first_tx);
1398 			if (r == 0)
1399 				r = 0.0001;
1400 			if (t == 0)
1401 				t = 0.0001;
1402 			(void)printf("  %.1f packets/sec sent, "
1403 				     " %.1f packets/sec received\n",
1404 				     ntransmitted/t, nreceived/r);
1405 		}
1406 	}
1407 }
1408 
1409 
1410 /*
1411  * Print statistics when SIGINFO is received.
1412  */
1413 /* ARGSUSED */
1414 static void
1415 prtsig(int dummy)
1416 {
1417 
1418 	summary(0);
1419 #ifndef SIGINFO
1420 	(void)signal(SIGQUIT, prtsig);
1421 #endif
1422 }
1423 
1424 
1425 /*
1426  * On the first SIGINT, allow any outstanding packets to dribble in
1427  */
1428 static void
1429 prefinish(int sig)
1430 {
1431 	if (lastrcvd			/* quit now if caught up */
1432 	    || nreceived == 0)		/* or if remote is dead */
1433 		finish(0);
1434 
1435 	(void)signal(sig, finish);	/* do this only the 1st time */
1436 
1437 	if (npackets > ntransmitted)	/* let the normal limit work */
1438 		npackets = ntransmitted;
1439 }
1440 
1441 /*
1442  * Print statistics and give up.
1443  */
1444 /* ARGSUSED */
1445 static void
1446 finish(int dummy)
1447 {
1448 #ifdef SIGINFO
1449 	(void)signal(SIGINFO, SIG_DFL);
1450 #else
1451 	(void)signal(SIGQUIT, SIG_DFL);
1452 #endif
1453 
1454 	summary(1);
1455 	exit(nreceived > 0 ? 0 : 2);
1456 }
1457 
1458 static void
1459 blocksignals(void)
1460 {
1461 	if (sigprocmask(SIG_SETMASK, &blockmask, NULL) == -1) {
1462 		err(EXIT_FAILURE, "blocksignals: sigprocmask");
1463 	}
1464 }
1465 
1466 static void
1467 enablesignals(void)
1468 {
1469 	if (sigprocmask(SIG_SETMASK, &enablemask, NULL) == -1) {
1470 		err(EXIT_FAILURE, "enablesignals: sigprocmask");
1471 	}
1472 }
1473 
1474 
1475 static int				/* 0=do not print it */
1476 ck_pr_icmph(struct icmp *icp,
1477 	    struct sockaddr_in *from,
1478 	    int cc,
1479 	    int override)		/* 1=override VERBOSE if interesting */
1480 {
1481 	int	hlen;
1482 	struct ip ipb, *ip = &ipb;
1483 	struct icmp icp2b, *icp2 = &icp2b;
1484 	int res;
1485 
1486 	if (pingflags & F_VERBOSE) {
1487 		res = 1;
1488 		jiggle_flush(1);
1489 	} else {
1490 		res = 0;
1491 	}
1492 
1493 	(void) memcpy(ip, icp->icmp_data, sizeof(*ip));
1494 	hlen = ip->ip_hl << 2;
1495 	if (ip->ip_p == IPPROTO_ICMP
1496 	    && hlen + 6 <= cc) {
1497 		(void) memcpy(icp2, &icp->icmp_data[hlen], sizeof(*icp2));
1498 		if (icp2->icmp_id == ident) {
1499 			/* remember to clear route cached in kernel
1500 			 * if this non-Echo-Reply ICMP message was for one
1501 			 * of our packets.
1502 			 */
1503 			clear_cache.tv_sec = 0;
1504 
1505 			if (!res && override
1506 			    && (pingflags & (F_QUIET|F_SEMI_QUIET)) == 0) {
1507 				jiggle_flush(1);
1508 				(void)printf("%d bytes from %s: ",
1509 					     cc, pr_addr(&from->sin_addr));
1510 				res = 1;
1511 			}
1512 		}
1513 	}
1514 
1515 	return res;
1516 }
1517 
1518 
1519 /*
1520  *  Print a descriptive string about an ICMP header other than an echo reply.
1521  */
1522 static int				/* 0=printed nothing */
1523 pr_icmph(struct icmp *icp,
1524 	 struct sockaddr_in *from,
1525 	 int cc)
1526 {
1527 	switch (icp->icmp_type ) {
1528 	case ICMP_UNREACH:
1529 		if (!ck_pr_icmph(icp, from, cc, 1))
1530 			return 0;
1531 		switch (icp->icmp_code) {
1532 		case ICMP_UNREACH_NET:
1533 			(void)printf("Destination Net Unreachable");
1534 			break;
1535 		case ICMP_UNREACH_HOST:
1536 			(void)printf("Destination Host Unreachable");
1537 			break;
1538 		case ICMP_UNREACH_PROTOCOL:
1539 			(void)printf("Destination Protocol Unreachable");
1540 			break;
1541 		case ICMP_UNREACH_PORT:
1542 			(void)printf("Destination Port Unreachable");
1543 			break;
1544 		case ICMP_UNREACH_NEEDFRAG:
1545 			(void)printf("frag needed and DF set.  Next MTU=%d",
1546 			       ntohs(icp->icmp_nextmtu));
1547 			break;
1548 		case ICMP_UNREACH_SRCFAIL:
1549 			(void)printf("Source Route Failed");
1550 			break;
1551 		case ICMP_UNREACH_NET_UNKNOWN:
1552 			(void)printf("Unreachable unknown net");
1553 			break;
1554 		case ICMP_UNREACH_HOST_UNKNOWN:
1555 			(void)printf("Unreachable unknown host");
1556 			break;
1557 		case ICMP_UNREACH_ISOLATED:
1558 			(void)printf("Unreachable host isolated");
1559 			break;
1560 		case ICMP_UNREACH_NET_PROHIB:
1561 			(void)printf("Net prohibited access");
1562 			break;
1563 		case ICMP_UNREACH_HOST_PROHIB:
1564 			(void)printf("Host prohibited access");
1565 			break;
1566 		case ICMP_UNREACH_TOSNET:
1567 			(void)printf("Bad TOS for net");
1568 			break;
1569 		case ICMP_UNREACH_TOSHOST:
1570 			(void)printf("Bad TOS for host");
1571 			break;
1572 		case 13:
1573 			(void)printf("Communication prohibited");
1574 			break;
1575 		case 14:
1576 			(void)printf("Host precedence violation");
1577 			break;
1578 		case 15:
1579 			(void)printf("Precedence cutoff");
1580 			break;
1581 		default:
1582 			(void)printf("Bad Destination Unreachable Code: %d",
1583 				     icp->icmp_code);
1584 			break;
1585 		}
1586 		/* Print returned IP header information */
1587 		pr_retip(icp, cc);
1588 		break;
1589 
1590 	case ICMP_SOURCEQUENCH:
1591 		if (!ck_pr_icmph(icp, from, cc, 1))
1592 			return 0;
1593 		(void)printf("Source Quench");
1594 		pr_retip(icp, cc);
1595 		break;
1596 
1597 	case ICMP_REDIRECT:
1598 		if (!ck_pr_icmph(icp, from, cc, 1))
1599 			return 0;
1600 		switch (icp->icmp_code) {
1601 		case ICMP_REDIRECT_NET:
1602 			(void)printf("Redirect Network");
1603 			break;
1604 		case ICMP_REDIRECT_HOST:
1605 			(void)printf("Redirect Host");
1606 			break;
1607 		case ICMP_REDIRECT_TOSNET:
1608 			(void)printf("Redirect Type of Service and Network");
1609 			break;
1610 		case ICMP_REDIRECT_TOSHOST:
1611 			(void)printf("Redirect Type of Service and Host");
1612 			break;
1613 		default:
1614 			(void)printf("Redirect--Bad Code: %d", icp->icmp_code);
1615 			break;
1616 		}
1617 		(void)printf(" New router addr: %s",
1618 			     pr_addr(&icp->icmp_hun.ih_gwaddr));
1619 		pr_retip(icp, cc);
1620 		break;
1621 
1622 	case ICMP_ECHO:
1623 		if (!ck_pr_icmph(icp, from, cc, 0))
1624 			return 0;
1625 		(void)printf("Echo Request: ID=%d seq=%d",
1626 			     ntohs(icp->icmp_id), ntohs(icp->icmp_seq));
1627 		break;
1628 
1629 	case ICMP_ECHOREPLY:
1630 		/* displaying other's pings is too noisey */
1631 #if 0
1632 		if (!ck_pr_icmph(icp, from, cc, 0))
1633 			return 0;
1634 		(void)printf("Echo Reply: ID=%d seq=%d",
1635 			     ntohs(icp->icmp_id), ntohs(icp->icmp_seq));
1636 		break;
1637 #else
1638 		return 0;
1639 #endif
1640 
1641 	case ICMP_ROUTERADVERT:
1642 		if (!ck_pr_icmph(icp, from, cc, 0))
1643 			return 0;
1644 		(void)printf("Router Discovery Advert");
1645 		break;
1646 
1647 	case ICMP_ROUTERSOLICIT:
1648 		if (!ck_pr_icmph(icp, from, cc, 0))
1649 			return 0;
1650 		(void)printf("Router Discovery Solicit");
1651 		break;
1652 
1653 	case ICMP_TIMXCEED:
1654 		if (!ck_pr_icmph(icp, from, cc, 1))
1655 			return 0;
1656 		switch (icp->icmp_code ) {
1657 		case ICMP_TIMXCEED_INTRANS:
1658 			(void)printf("Time To Live exceeded");
1659 			break;
1660 		case ICMP_TIMXCEED_REASS:
1661 			(void)printf("Frag reassembly time exceeded");
1662 			break;
1663 		default:
1664 			(void)printf("Time exceeded, Bad Code: %d",
1665 				     icp->icmp_code);
1666 			break;
1667 		}
1668 		pr_retip(icp, cc);
1669 		break;
1670 
1671 	case ICMP_PARAMPROB:
1672 		if (!ck_pr_icmph(icp, from, cc, 1))
1673 			return 0;
1674 		(void)printf("Parameter problem: pointer = 0x%02x",
1675 			     icp->icmp_hun.ih_pptr);
1676 		pr_retip(icp, cc);
1677 		break;
1678 
1679 	case ICMP_TSTAMP:
1680 		if (!ck_pr_icmph(icp, from, cc, 0))
1681 			return 0;
1682 		(void)printf("Timestamp");
1683 		break;
1684 
1685 	case ICMP_TSTAMPREPLY:
1686 		if (!ck_pr_icmph(icp, from, cc, 0))
1687 			return 0;
1688 		(void)printf("Timestamp Reply");
1689 		break;
1690 
1691 	case ICMP_IREQ:
1692 		if (!ck_pr_icmph(icp, from, cc, 0))
1693 			return 0;
1694 		(void)printf("Information Request");
1695 		break;
1696 
1697 	case ICMP_IREQREPLY:
1698 		if (!ck_pr_icmph(icp, from, cc, 0))
1699 			return 0;
1700 		(void)printf("Information Reply");
1701 		break;
1702 
1703 	case ICMP_MASKREQ:
1704 		if (!ck_pr_icmph(icp, from, cc, 0))
1705 			return 0;
1706 		(void)printf("Address Mask Request");
1707 		break;
1708 
1709 	case ICMP_MASKREPLY:
1710 		if (!ck_pr_icmph(icp, from, cc, 0))
1711 			return 0;
1712 		(void)printf("Address Mask Reply");
1713 		break;
1714 
1715 	default:
1716 		if (!ck_pr_icmph(icp, from, cc, 0))
1717 			return 0;
1718 		(void)printf("Bad ICMP type: %d", icp->icmp_type);
1719 		if (pingflags & F_VERBOSE)
1720 			pr_iph(icp, cc);
1721 	}
1722 
1723 	return 1;
1724 }
1725 
1726 
1727 /*
1728  *  Print an IP header with options.
1729  */
1730 static void
1731 pr_iph(struct icmp *icp,
1732        int cc)
1733 {
1734 	int	hlen;
1735 	u_char	*cp;
1736 	struct ip ipb, *ip = &ipb;
1737 
1738 	(void) memcpy(ip, icp->icmp_data, sizeof(*ip));
1739 
1740 	hlen = ip->ip_hl << 2;
1741 	cp = (u_char *) &icp->icmp_data[20];	/* point to options */
1742 
1743 	(void)printf("\n Vr HL TOS  Len   ID Flg  off TTL Pro  cks      Src	     Dst\n");
1744 	(void)printf("  %1x  %1x  %02x %04x %04x",
1745 		     ip->ip_v, ip->ip_hl, ip->ip_tos, ip->ip_len, ip->ip_id);
1746 	(void)printf("   %1x %04x",
1747 		     ((ip->ip_off)&0xe000)>>13, (ip->ip_off)&0x1fff);
1748 	(void)printf("  %02x  %02x %04x",
1749 		     ip->ip_ttl, ip->ip_p, ip->ip_sum);
1750 	(void)printf(" %15s ",
1751 		     inet_ntoa(*(struct in_addr *)&ip->ip_src.s_addr));
1752 	(void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_dst.s_addr));
1753 	/* dump any option bytes */
1754 	while (hlen-- > 20 && cp < (u_char*)icp+cc) {
1755 		(void)printf("%02x", *cp++);
1756 	}
1757 }
1758 
1759 /*
1760  * Print an ASCII host address starting from a string of bytes.
1761  */
1762 static void
1763 pr_saddr(u_char *cp)
1764 {
1765 	n_long l;
1766 	struct in_addr addr;
1767 
1768 	l = (u_char)*++cp;
1769 	l = (l<<8) + (u_char)*++cp;
1770 	l = (l<<8) + (u_char)*++cp;
1771 	l = (l<<8) + (u_char)*++cp;
1772 	addr.s_addr = htonl(l);
1773 	(void)printf("\t%s", (l == 0) ? "0.0.0.0" : pr_addr(&addr));
1774 }
1775 
1776 
1777 /*
1778  *  Return an ASCII host address
1779  *  as a dotted quad and optionally with a hostname
1780  */
1781 static char *
1782 pr_addr(struct in_addr *addr)		/* in network order */
1783 {
1784 	struct	hostent	*hp;
1785 	static	char buf[MAXHOSTNAMELEN+4+16+1];
1786 
1787 	if ((pingflags & F_NUMERIC)
1788 	    || !(hp = gethostbyaddr((char *)addr, sizeof(*addr), AF_INET))) {
1789 		(void)snprintf(buf, sizeof(buf), "%s", inet_ntoa(*addr));
1790 	} else {
1791 		(void)snprintf(buf, sizeof(buf), "%s (%s)", hp->h_name,
1792 		    inet_ntoa(*addr));
1793 	}
1794 
1795 	return buf;
1796 }
1797 
1798 /*
1799  *  Dump some info on a returned (via ICMP) IP packet.
1800  */
1801 static void
1802 pr_retip(struct icmp *icp,
1803 	 int cc)
1804 {
1805 	int	hlen;
1806 	u_char	*cp;
1807 	struct ip ipb, *ip = &ipb;
1808 
1809 	(void) memcpy(ip, icp->icmp_data, sizeof(*ip));
1810 
1811 	if (pingflags & F_VERBOSE)
1812 		pr_iph(icp, cc);
1813 
1814 	hlen = ip->ip_hl << 2;
1815 	cp = (u_char *) &icp->icmp_data[hlen];
1816 
1817 	if (ip->ip_p == IPPROTO_TCP) {
1818 		if (pingflags & F_VERBOSE)
1819 			(void)printf("\n  TCP: from port %u, to port %u",
1820 				     (*cp*256+*(cp+1)), (*(cp+2)*256+*(cp+3)));
1821 	} else if (ip->ip_p == IPPROTO_UDP) {
1822 		if (pingflags & F_VERBOSE)
1823 			(void)printf("\n  UDP: from port %u, to port %u",
1824 				     (*cp*256+*(cp+1)), (*(cp+2)*256+*(cp+3)));
1825 	} else if (ip->ip_p == IPPROTO_ICMP) {
1826 		struct icmp icp2;
1827 		(void) memcpy(&icp2, cp, sizeof(icp2));
1828 		if (icp2.icmp_type == ICMP_ECHO) {
1829 			if (pingflags & F_VERBOSE)
1830 				(void)printf("\n  ID=%u icmp_seq=%u",
1831 					     ntohs((u_int16_t)icp2.icmp_id),
1832 					     ntohs((u_int16_t)icp2.icmp_seq));
1833 			else
1834 				(void)printf(" for icmp_seq=%u",
1835 					     ntohs((u_int16_t)icp2.icmp_seq));
1836 		}
1837 	}
1838 }
1839 
1840 static void
1841 fill(void)
1842 {
1843 	int i, j, k;
1844 	char *cp;
1845 	int pat[16];
1846 
1847 	for (cp = fill_pat; *cp != '\0'; cp++) {
1848 		if (!isxdigit((unsigned char)*cp))
1849 			break;
1850 	}
1851 	if (cp == fill_pat || *cp != '\0' || (cp-fill_pat) > 16*2) {
1852 		(void)fflush(stdout);
1853 		errx(EXIT_FAILURE, "\"-p %s\": patterns must be specified with"
1854 		     " 1-32 hex digits\n",
1855 		     fill_pat);
1856 	}
1857 
1858 	i = sscanf(fill_pat,
1859 		   "%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x",
1860 		    &pat[0], &pat[1], &pat[2], &pat[3],
1861 		    &pat[4], &pat[5], &pat[6], &pat[7],
1862 		    &pat[8], &pat[9], &pat[10], &pat[11],
1863 		    &pat[12], &pat[13], &pat[14], &pat[15]);
1864 
1865 	for (k = phdrlen, j = 0; k < datalen; k++) {
1866 		opack_icmp.icmp_data[k] = pat[j];
1867 		if (++j >= i)
1868 			j = 0;
1869 	}
1870 
1871 	if (!(pingflags & F_QUIET)) {
1872 		(void)printf("PATTERN: 0x");
1873 		for (j=0; j<i; j++)
1874 			(void)printf("%02x",
1875 				     (u_char)opack_icmp.icmp_data[phdrlen + j]);
1876 		(void)printf("\n");
1877 	}
1878 
1879 }
1880 
1881 
1882 static void
1883 rnd_fill(void)
1884 {
1885 	static u_int32_t rnd;
1886 	int i;
1887 
1888 	for (i = phdrlen; i < datalen; i++) {
1889 		rnd = (3141592621U * rnd + 663896637U);
1890 		opack_icmp.icmp_data[i] = rnd>>24;
1891 	}
1892 }
1893 
1894 
1895 static void
1896 gethost(const char *arg,
1897 	const char *name,
1898 	struct sockaddr_in *sa,
1899 	char *realname,
1900 	int realname_len)
1901 {
1902 	struct hostent *hp;
1903 
1904 	(void)memset(sa, 0, sizeof(*sa));
1905 	sa->sin_family = AF_INET;
1906 	sa->sin_len = sizeof(struct sockaddr_in);
1907 
1908 	/* If it is an IP address, try to convert it to a name to
1909 	 * have something nice to display.
1910 	 */
1911 	if (inet_aton(name, &sa->sin_addr) != 0) {
1912 		if (realname) {
1913 			if (pingflags & F_NUMERIC)
1914 				hp = 0;
1915 			else
1916 				hp = gethostbyaddr((char *)&sa->sin_addr,
1917 				    sizeof(sa->sin_addr), AF_INET);
1918 			(void)strlcpy(realname, hp ? hp->h_name : name,
1919 			    realname_len);
1920 		}
1921 		return;
1922 	}
1923 
1924 	hp = gethostbyname(name);
1925 	if (!hp)
1926 		errx(EXIT_FAILURE, "Cannot resolve \"%s\" (%s)",
1927 		    name, hstrerror(h_errno));
1928 
1929 	if (hp->h_addrtype != AF_INET)
1930 		errx(EXIT_FAILURE, "%s only supported with IP", arg);
1931 
1932 	(void)memcpy(&sa->sin_addr, hp->h_addr, sizeof(sa->sin_addr));
1933 
1934 	if (realname)
1935 		(void)strlcpy(realname, hp->h_name, realname_len);
1936 }
1937 
1938 
1939 static void
1940 usage(void)
1941 {
1942 #ifdef IPSEC
1943 #ifdef IPSEC_POLICY_IPSEC
1944 #define IPSECOPT	"\n     [-E policy] "
1945 #else
1946 #define IPSECOPT	"\n     [-AE] "
1947 #endif /*IPSEC_POLICY_IPSEC*/
1948 #else
1949 #define IPSECOPT	""
1950 #endif /*IPSEC*/
1951 
1952 	(void)fprintf(stderr, "usage: \n"
1953 	    "%s [-aCDdfLnoPQqRrv] [-c count] [-g gateway] [-h host]"
1954 	    " [-I addr] [-i interval]\n"
1955 	    "     [-l preload] [-p pattern] [-s size] [-T ttl] [-t tos]"
1956 	    " [-w maxwait] " IPSECOPT "host\n",
1957 	    getprogname());
1958 	exit(1);
1959 }
1960