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