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