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