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