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