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