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