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