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