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