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