Home | History | Annotate | Line # | Download | only in ping
ping.c revision 1.13
      1 /*	$NetBSD: ping.c,v 1.13 1995/03/18 14:59:16 cgd 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 #ifndef lint
     40 static char copyright[] =
     41 "@(#) Copyright (c) 1989, 1993\n\
     42 	The Regents of the University of California.  All rights reserved.\n";
     43 #endif /* not lint */
     44 
     45 #ifndef lint
     46 #if 0
     47 static char sccsid[] = "@(#)ping.c	8.1 (Berkeley) 6/5/93";
     48 #else
     49 static char rcsid[] = "$NetBSD: ping.c,v 1.13 1995/03/18 14:59:16 cgd Exp $";
     50 #endif
     51 #endif /* not lint */
     52 
     53 /*
     54  *			P I N G . C
     55  *
     56  * Using the InterNet Control Message Protocol (ICMP) "ECHO" facility,
     57  * measure round-trip-delays and packet loss across network paths.
     58  *
     59  * Author -
     60  *	Mike Muuss
     61  *	U. S. Army Ballistic Research Laboratory
     62  *	December, 1983
     63  *
     64  * Status -
     65  *	Public Domain.  Distribution Unlimited.
     66  * Bugs -
     67  *	More statistics could always be gathered.
     68  *	This program has to run SUID to ROOT to access the ICMP socket.
     69  */
     70 
     71 #include <sys/param.h>
     72 #include <sys/queue.h>
     73 #include <sys/socket.h>
     74 #include <sys/file.h>
     75 #include <sys/time.h>
     76 #include <sys/signal.h>
     77 
     78 #include <netinet/in_systm.h>
     79 #include <netinet/in.h>
     80 #include <netinet/ip.h>
     81 #include <netinet/ip_icmp.h>
     82 #include <netinet/ip_var.h>
     83 #include <arpa/inet.h>
     84 #include <netdb.h>
     85 #include <unistd.h>
     86 #include <stdio.h>
     87 #include <ctype.h>
     88 #include <err.h>
     89 #include <errno.h>
     90 #include <string.h>
     91 #include <stdlib.h>
     92 
     93 #define	DEFDATALEN	(64 - 8)	/* default data length */
     94 #define	MAXIPLEN	60
     95 #define	MAXICMPLEN	76
     96 #define	MAXPACKET	(65536 - 60 - 8)/* max packet size */
     97 #define	MAXWAIT		10		/* max seconds to wait for response */
     98 #define	NROUTES		9		/* number of record route slots */
     99 
    100 #define	A(bit)		rcvd_tbl[(bit)>>3]	/* identify byte in array */
    101 #define	B(bit)		(1 << ((bit) & 0x07))	/* identify bit in byte */
    102 #define	SET(bit)	(A(bit) |= B(bit))
    103 #define	CLR(bit)	(A(bit) &= (~B(bit)))
    104 #define	TST(bit)	(A(bit) & B(bit))
    105 
    106 /* various options */
    107 int options;
    108 #define	F_FLOOD		0x001
    109 #define	F_INTERVAL	0x002
    110 #define	F_NUMERIC	0x004
    111 #define	F_PINGFILLED	0x008
    112 #define	F_QUIET		0x010
    113 #define	F_RROUTE	0x020
    114 #define	F_SO_DEBUG	0x040
    115 #define	F_SO_DONTROUTE	0x080
    116 #define	F_VERBOSE	0x100
    117 
    118 /* multicast options */
    119 int moptions;
    120 #define	MULTICAST_NOLOOP	0x001
    121 #define	MULTICAST_TTL		0x002
    122 #define	MULTICAST_IF		0x004
    123 
    124 /*
    125  * MAX_DUP_CHK is the number of bits in received table, i.e. the maximum
    126  * number of received sequence numbers we can keep track of.  Change 128
    127  * to 8192 for complete accuracy...
    128  */
    129 #define	MAX_DUP_CHK	(8 * 128)
    130 int mx_dup_ck = MAX_DUP_CHK;
    131 char rcvd_tbl[MAX_DUP_CHK / 8];
    132 
    133 struct sockaddr whereto;	/* who to ping */
    134 int datalen = DEFDATALEN;
    135 int s;				/* socket file descriptor */
    136 u_char outpack[MAXPACKET];
    137 char BSPACE = '\b';		/* characters written for flood */
    138 char DOT = '.';
    139 char *hostname;
    140 int ident;			/* process id to identify our packets */
    141 
    142 /* counters */
    143 long npackets;			/* max packets to transmit */
    144 long nreceived;			/* # of packets we got back */
    145 long nrepeats;			/* number of duplicates */
    146 long ntransmitted;		/* sequence # for outbound packets = #sent */
    147 int interval = 1;		/* interval between packets */
    148 
    149 /* timing */
    150 int timing;			/* flag to do timing */
    151 double tmin = 999999999.0;	/* minimum round trip time */
    152 double tmax = 0.0;		/* maximum round trip time */
    153 double tsum = 0.0;		/* sum of all times, for doing average */
    154 
    155 void fill __P((char *, char *));
    156 void catcher(), finish();
    157 int in_cksum __P((u_short *, int));
    158 void pinger();
    159 char *pr_addr __P((u_long));
    160 void pr_icmph __P((struct icmp *));
    161 void pr_pack __P((char *, int, struct sockaddr_in *));
    162 void pr_retip __P((struct ip *));
    163 void tvsub __P((struct timeval *, struct timeval *));
    164 void usage();
    165 
    166 int
    167 main(argc, argv)
    168 	int argc;
    169 	char **argv;
    170 {
    171 	extern int errno, optind;
    172 	extern char *optarg;
    173 	struct timeval timeout;
    174 	struct hostent *hp;
    175 	struct sockaddr_in *to;
    176 	struct protoent *proto;
    177 	struct in_addr ifaddr;
    178 	register int i;
    179 	int ch, fdmask, hold, packlen, preload;
    180 	u_char *datap, *packet;
    181 	char *target, hnamebuf[MAXHOSTNAMELEN];
    182 	u_char ttl, loop = 1;
    183 #ifdef IP_OPTIONS
    184 	char rspace[3 + 4 * NROUTES + 1];	/* record route space */
    185 #endif
    186 
    187 	preload = 0;
    188 	datap = &outpack[8 + sizeof(struct timeval)];
    189 	while ((ch = getopt(argc, argv, "I:LRc:dfh:i:l:np:qrs:t:v")) != EOF)
    190 		switch(ch) {
    191 		case 'c':
    192 			npackets = atoi(optarg);
    193 			if (npackets <= 0)
    194 				errx(1, "bad number of packets to transmit: %s",
    195 				    optarg);
    196 			break;
    197 		case 'd':
    198 			options |= F_SO_DEBUG;
    199 			break;
    200 		case 'f':
    201 			if (getuid())
    202 				errx(1, "%s", strerror(EPERM));
    203 			options |= F_FLOOD;
    204 			setbuf(stdout, (char *)NULL);
    205 			break;
    206 		case 'I':
    207 			if (inet_aton(optarg, &ifaddr) == 0)
    208 				errx(1, "bad interface address: %s", optarg);
    209 			moptions |= MULTICAST_IF;
    210 			break;
    211 		case 'i':		/* wait between sending packets */
    212 			interval = atoi(optarg);
    213 			if (interval <= 0)
    214 				errx(1, "bad timing interval: %s", optarg);
    215 			options |= F_INTERVAL;
    216 			break;
    217 		case 'L':
    218 			moptions |= MULTICAST_NOLOOP;
    219 			loop = 0;
    220 			break;
    221 		case 'l':
    222 			preload = atoi(optarg);
    223 			if (preload < 0)
    224 				errx(1, "bad preload value: %s", optarg);
    225 			break;
    226 		case 'n':
    227 			options |= F_NUMERIC;
    228 			break;
    229 		case 'p':		/* fill buffer with user pattern */
    230 			options |= F_PINGFILLED;
    231 			fill((char *)datap, optarg);
    232 				break;
    233 		case 'q':
    234 			options |= F_QUIET;
    235 			break;
    236 		case 'R':
    237 			options |= F_RROUTE;
    238 			break;
    239 		case 'r':
    240 			options |= F_SO_DONTROUTE;
    241 			break;
    242 		case 's':		/* size of packet to send */
    243 			datalen = atoi(optarg);
    244 			if (datalen <= 0)
    245 				errx(1, "bad packet size: %s", optarg);
    246 			if (datalen > MAXPACKET)
    247 				errx(1, "packet size too large: %s", optarg);
    248 			break;
    249 		case 't':
    250 			ttl = atoi(optarg);
    251 			if (ttl <= 0)
    252 				errx(1, "bad ttl value: %s", optarg);
    253 			if (ttl > 255)
    254 				errx(1, "ttl value too large: %s", optarg);
    255 			break;
    256 		case 'v':
    257 			options |= F_VERBOSE;
    258 			break;
    259 		default:
    260 			usage();
    261 		}
    262 	argc -= optind;
    263 	argv += optind;
    264 
    265 	if (argc != 1)
    266 		usage();
    267 	target = *argv;
    268 
    269 	memset(&whereto, 0, sizeof(struct sockaddr));
    270 	to = (struct sockaddr_in *)&whereto;
    271 	to->sin_family = AF_INET;
    272 	to->sin_addr.s_addr = inet_addr(target);
    273 	if (to->sin_addr.s_addr != (u_int)-1)
    274 		hostname = target;
    275 	else {
    276 		hp = gethostbyname(target);
    277 		if (!hp)
    278 			errx(1, "unknown host: %s", target);
    279 		to->sin_family = hp->h_addrtype;
    280 		memcpy(&to->sin_addr, hp->h_addr, hp->h_length);
    281 		(void)strncpy(hnamebuf, hp->h_name, sizeof(hnamebuf) - 1);
    282 		hostname = hnamebuf;
    283 	}
    284 
    285 	if (options & F_FLOOD && options & F_INTERVAL)
    286 		errx(1, "-f and -i options are incompatible");
    287 
    288 	if (datalen >= sizeof(struct timeval))	/* can we time transfer */
    289 		timing = 1;
    290 	packlen = datalen + MAXIPLEN + MAXICMPLEN;
    291 	if (!(packet = (u_char *)malloc((u_int)packlen)))
    292 		err(1, "malloc");
    293 	if (!(options & F_PINGFILLED))
    294 		for (i = 8; i < datalen; ++i)
    295 			*datap++ = i;
    296 
    297 	ident = getpid() & 0xFFFF;
    298 
    299 	if (!(proto = getprotobyname("icmp")))
    300 		errx(1, "unknown protocol icmp");
    301 	if ((s = socket(AF_INET, SOCK_RAW, proto->p_proto)) < 0)
    302 		err(1, "socket");
    303 	hold = 1;
    304 	if (options & F_SO_DEBUG)
    305 		(void)setsockopt(s, SOL_SOCKET, SO_DEBUG, (char *)&hold,
    306 		    sizeof(hold));
    307 	if (options & F_SO_DONTROUTE)
    308 		(void)setsockopt(s, SOL_SOCKET, SO_DONTROUTE, (char *)&hold,
    309 		    sizeof(hold));
    310 
    311 	/* record route option */
    312 	if (options & F_RROUTE) {
    313 #ifdef IP_OPTIONS
    314 		rspace[IPOPT_OPTVAL] = IPOPT_RR;
    315 		rspace[IPOPT_OLEN] = sizeof(rspace)-1;
    316 		rspace[IPOPT_OFFSET] = IPOPT_MINOFF;
    317 		if (setsockopt(s, IPPROTO_IP, IP_OPTIONS, rspace,
    318 		    sizeof(rspace)) < 0) {
    319 			perror("ping: record route");
    320 			exit(1);
    321 		}
    322 #else
    323 		errx(1, "record route not available in this implementation");
    324 #endif /* IP_OPTIONS */
    325 	}
    326 
    327 	if ((moptions & MULTICAST_NOLOOP) &&
    328 	    setsockopt(s, IPPROTO_IP, IP_MULTICAST_LOOP, &loop,
    329 		       sizeof(loop)) < 0)
    330 		err(1, "setsockopt IP_MULTICAST_LOOP");
    331 	if ((moptions & MULTICAST_TTL) &&
    332 	    setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL, &ttl,
    333 		       sizeof(ttl)) < 0)
    334 		err(1, "setsockopt IP_MULTICAST_TTL");
    335 	if ((moptions & MULTICAST_IF) &&
    336 	    setsockopt(s, IPPROTO_IP, IP_MULTICAST_IF, &ifaddr,
    337 		       sizeof(ifaddr)) < 0)
    338 		err(1, "setsockopt IP_MULTICAST_IF");
    339 
    340 	/*
    341 	 * When pinging the broadcast address, you can get a lot of answers.
    342 	 * Doing something so evil is useful if you are trying to stress the
    343 	 * ethernet, or just want to fill the arp cache to get some stuff for
    344 	 * /etc/ethers.
    345 	 */
    346 	hold = 48 * 1024;
    347 	(void)setsockopt(s, SOL_SOCKET, SO_RCVBUF, (char *)&hold,
    348 	    sizeof(hold));
    349 
    350 	if (to->sin_family == AF_INET)
    351 		(void)printf("PING %s (%s): %d data bytes\n", hostname,
    352 		    inet_ntoa(*(struct in_addr *)&to->sin_addr.s_addr),
    353 		    datalen);
    354 	else
    355 		(void)printf("PING %s: %d data bytes\n", hostname, datalen);
    356 
    357 	(void)signal(SIGINT, finish);
    358 	(void)signal(SIGALRM, catcher);
    359 
    360 	while (preload--)		/* fire off them quickies */
    361 		pinger();
    362 
    363 	if ((options & F_FLOOD) == 0)
    364 		catcher();		/* start things going */
    365 
    366 	for (;;) {
    367 		struct sockaddr_in from;
    368 		register int cc;
    369 		int fromlen;
    370 
    371 		if (options & F_FLOOD) {
    372 			pinger();
    373 			timeout.tv_sec = 0;
    374 			timeout.tv_usec = 10000;
    375 			fdmask = 1 << s;
    376 			if (select(s + 1, (fd_set *)&fdmask, (fd_set *)NULL,
    377 			    (fd_set *)NULL, &timeout) < 1)
    378 				continue;
    379 		}
    380 		fromlen = sizeof(from);
    381 		if ((cc = recvfrom(s, (char *)packet, packlen, 0,
    382 		    (struct sockaddr *)&from, &fromlen)) < 0) {
    383 			if (errno == EINTR)
    384 				continue;
    385 			perror("ping: recvfrom");
    386 			continue;
    387 		}
    388 		pr_pack((char *)packet, cc, &from);
    389 		if (npackets && nreceived >= npackets)
    390 			break;
    391 	}
    392 	finish();
    393 	/* NOTREACHED */
    394 	exit(0);	/* Make the compiler happy */
    395 }
    396 
    397 /*
    398  * catcher --
    399  *	This routine causes another PING to be transmitted, and then
    400  * schedules another SIGALRM for 1 second from now.
    401  *
    402  * bug --
    403  *	Our sense of time will slowly skew (i.e., packets will not be
    404  * launched exactly at 1-second intervals).  This does not affect the
    405  * quality of the delay and loss statistics.
    406  */
    407 void
    408 catcher()
    409 {
    410 	int waittime;
    411 
    412 	pinger();
    413 	(void)signal(SIGALRM, catcher);
    414 	if (!npackets || ntransmitted < npackets)
    415 		alarm((u_int)interval);
    416 	else {
    417 		if (nreceived) {
    418 			waittime = 2 * tmax / 1000;
    419 			if (!waittime)
    420 				waittime = 1;
    421 		} else
    422 			waittime = MAXWAIT;
    423 		(void)signal(SIGALRM, finish);
    424 		(void)alarm((u_int)waittime);
    425 	}
    426 }
    427 
    428 /*
    429  * pinger --
    430  *	Compose and transmit an ICMP ECHO REQUEST packet.  The IP packet
    431  * will be added on by the kernel.  The ID field is our UNIX process ID,
    432  * and the sequence number is an ascending integer.  The first 8 bytes
    433  * of the data portion are used to hold a UNIX "timeval" struct in VAX
    434  * byte-order, to compute the round-trip time.
    435  */
    436 void
    437 pinger()
    438 {
    439 	register struct icmp *icp;
    440 	register int cc;
    441 	int i;
    442 
    443 	icp = (struct icmp *)outpack;
    444 	icp->icmp_type = ICMP_ECHO;
    445 	icp->icmp_code = 0;
    446 	icp->icmp_cksum = 0;
    447 	icp->icmp_seq = ntransmitted++;
    448 	icp->icmp_id = ident;			/* ID */
    449 
    450 	CLR(icp->icmp_seq % mx_dup_ck);
    451 
    452 	if (timing)
    453 		(void)gettimeofday((struct timeval *)&outpack[8],
    454 		    (struct timezone *)NULL);
    455 
    456 	cc = datalen + 8;			/* skips ICMP portion */
    457 
    458 	/* compute ICMP checksum here */
    459 	icp->icmp_cksum = in_cksum((u_short *)icp, cc);
    460 
    461 	i = sendto(s, (char *)outpack, cc, 0, &whereto,
    462 	    sizeof(struct sockaddr));
    463 
    464 	if (i < 0 || i != cc)  {
    465 		if (i < 0)
    466 			perror("ping: sendto");
    467 		(void)printf("ping: wrote %s %d chars, ret=%d\n",
    468 		    hostname, cc, i);
    469 	}
    470 	if (!(options & F_QUIET) && options & F_FLOOD)
    471 		(void)write(STDOUT_FILENO, &DOT, 1);
    472 }
    473 
    474 /*
    475  * pr_pack --
    476  *	Print out the packet, if it came from us.  This logic is necessary
    477  * because ALL readers of the ICMP socket get a copy of ALL ICMP packets
    478  * which arrive ('tis only fair).  This permits multiple copies of this
    479  * program to be run without having intermingled output (or statistics!).
    480  */
    481 void
    482 pr_pack(buf, cc, from)
    483 	char *buf;
    484 	int cc;
    485 	struct sockaddr_in *from;
    486 {
    487 	register struct icmp *icp;
    488 	register u_long l;
    489 	register int i, j;
    490 	register u_char *cp,*dp;
    491 	static int old_rrlen;
    492 	static char old_rr[MAX_IPOPTLEN];
    493 	struct ip *ip;
    494 	struct timeval tv, *tp;
    495 	double triptime;
    496 	int hlen, dupflag;
    497 
    498 	(void)gettimeofday(&tv, (struct timezone *)NULL);
    499 
    500 	/* Check the IP header */
    501 	ip = (struct ip *)buf;
    502 	hlen = ip->ip_hl << 2;
    503 	if (cc < hlen + ICMP_MINLEN) {
    504 		if (options & F_VERBOSE)
    505 			warnx("packet too short (%d bytes) from %s", cc,
    506 			  inet_ntoa(*(struct in_addr *)&from->sin_addr.s_addr));
    507 		return;
    508 	}
    509 
    510 	/* Now the ICMP part */
    511 	cc -= hlen;
    512 	icp = (struct icmp *)(buf + hlen);
    513 	if (icp->icmp_type == ICMP_ECHOREPLY) {
    514 		if (icp->icmp_id != ident)
    515 			return;			/* 'Twas not our ECHO */
    516 		++nreceived;
    517 		if (timing) {
    518 #ifndef icmp_data
    519 			tp = (struct timeval *)&icp->icmp_ip;
    520 #else
    521 			tp = (struct timeval *)icp->icmp_data;
    522 #endif
    523 			tvsub(&tv, tp);
    524 			triptime = ((double)tv.tv_sec) * 1000.0 +
    525 			    ((double)tv.tv_usec) / 1000.0;
    526 			tsum += triptime;
    527 			if (triptime < tmin)
    528 				tmin = triptime;
    529 			if (triptime > tmax)
    530 				tmax = triptime;
    531 		}
    532 
    533 		if (TST(icp->icmp_seq % mx_dup_ck)) {
    534 			++nrepeats;
    535 			--nreceived;
    536 			dupflag = 1;
    537 		} else {
    538 			SET(icp->icmp_seq % mx_dup_ck);
    539 			dupflag = 0;
    540 		}
    541 
    542 		if (options & F_QUIET)
    543 			return;
    544 
    545 		if (options & F_FLOOD)
    546 			(void)write(STDOUT_FILENO, &BSPACE, 1);
    547 		else {
    548 			(void)printf("%d bytes from %s: icmp_seq=%u", cc,
    549 			   inet_ntoa(*(struct in_addr *)&from->sin_addr.s_addr),
    550 			   icp->icmp_seq);
    551 			(void)printf(" ttl=%d", ip->ip_ttl);
    552 			if (timing)
    553 				(void)printf(" time=%.3f ms", triptime);
    554 			if (dupflag)
    555 				(void)printf(" (DUP!)");
    556 			/* check the data */
    557 			cp = (u_char*)&icp->icmp_data[8];
    558 			dp = &outpack[8 + sizeof(struct timeval)];
    559 			for (i = 8; i < datalen; ++i, ++cp, ++dp) {
    560 				if (*cp != *dp) {
    561 	(void)printf("\nwrong data byte #%d should be 0x%x but was 0x%x",
    562 	    i, *dp, *cp);
    563 					cp = (u_char*)&icp->icmp_data[0];
    564 					for (i = 8; i < datalen; ++i, ++cp) {
    565 						if ((i % 32) == 8)
    566 							(void)printf("\n\t");
    567 						(void)printf("%x ", *cp);
    568 					}
    569 					break;
    570 				}
    571 			}
    572 		}
    573 	} else {
    574 		/* We've got something other than an ECHOREPLY */
    575 		if (!(options & F_VERBOSE))
    576 			return;
    577 		(void)printf("%d bytes from %s: ", cc,
    578 		    pr_addr(from->sin_addr.s_addr));
    579 		pr_icmph(icp);
    580 	}
    581 
    582 	/* Display any IP options */
    583 	cp = (u_char *)buf + sizeof(struct ip);
    584 
    585 	for (; hlen > (int)sizeof(struct ip); --hlen, ++cp)
    586 		switch (*cp) {
    587 		case IPOPT_EOL:
    588 			hlen = 0;
    589 			break;
    590 		case IPOPT_LSRR:
    591 			(void)printf("\nLSRR: ");
    592 			hlen -= 2;
    593 			j = *++cp;
    594 			++cp;
    595 			if (j > IPOPT_MINOFF)
    596 				for (;;) {
    597 					l = *++cp;
    598 					l = (l<<8) + *++cp;
    599 					l = (l<<8) + *++cp;
    600 					l = (l<<8) + *++cp;
    601 					if (l == 0)
    602 						(void)printf("\t0.0.0.0");
    603 				else
    604 					(void)printf("\t%s", pr_addr(ntohl(l)));
    605 				hlen -= 4;
    606 				j -= 4;
    607 				if (j <= IPOPT_MINOFF)
    608 					break;
    609 				(void)putchar('\n');
    610 			}
    611 			break;
    612 		case IPOPT_RR:
    613 			j = *++cp;		/* get length */
    614 			i = *++cp;		/* and pointer */
    615 			hlen -= 2;
    616 			if (i > j)
    617 				i = j;
    618 			i -= IPOPT_MINOFF;
    619 			if (i <= 0)
    620 				continue;
    621 			if (i == old_rrlen
    622 			    && cp == (u_char *)buf + sizeof(struct ip) + 2
    623 			    && !memcmp(cp, old_rr, i)
    624 			    && !(options & F_FLOOD)) {
    625 				(void)printf("\t(same route)");
    626 				i = ((i + 3) / 4) * 4;
    627 				hlen -= i;
    628 				cp += i;
    629 				break;
    630 			}
    631 			old_rrlen = i;
    632 			memcpy(old_rr, cp, i);
    633 			(void)printf("\nRR: ");
    634 			for (;;) {
    635 				l = *++cp;
    636 				l = (l<<8) + *++cp;
    637 				l = (l<<8) + *++cp;
    638 				l = (l<<8) + *++cp;
    639 				if (l == 0)
    640 					(void)printf("\t0.0.0.0");
    641 				else
    642 					(void)printf("\t%s", pr_addr(ntohl(l)));
    643 				hlen -= 4;
    644 				i -= 4;
    645 				if (i <= 0)
    646 					break;
    647 				(void)putchar('\n');
    648 			}
    649 			break;
    650 		case IPOPT_NOP:
    651 			(void)printf("\nNOP");
    652 			break;
    653 		default:
    654 			(void)printf("\nunknown option %x", *cp);
    655 			break;
    656 		}
    657 	if (!(options & F_FLOOD)) {
    658 		(void)putchar('\n');
    659 		(void)fflush(stdout);
    660 	}
    661 }
    662 
    663 /*
    664  * in_cksum --
    665  *	Checksum routine for Internet Protocol family headers (C Version)
    666  */
    667 int
    668 in_cksum(addr, len)
    669 	u_short *addr;
    670 	int len;
    671 {
    672 	register int nleft = len;
    673 	register u_short *w = addr;
    674 	register int sum = 0;
    675 	u_short answer = 0;
    676 
    677 	/*
    678 	 * Our algorithm is simple, using a 32 bit accumulator (sum), we add
    679 	 * sequential 16 bit words to it, and at the end, fold back all the
    680 	 * carry bits from the top 16 bits into the lower 16 bits.
    681 	 */
    682 	while (nleft > 1)  {
    683 		sum += *w++;
    684 		nleft -= 2;
    685 	}
    686 
    687 	/* mop up an odd byte, if necessary */
    688 	if (nleft == 1) {
    689 		*(u_char *)(&answer) = *(u_char *)w ;
    690 		sum += answer;
    691 	}
    692 
    693 	/* add back carry outs from top 16 bits to low 16 bits */
    694 	sum = (sum >> 16) + (sum & 0xffff);	/* add hi 16 to low 16 */
    695 	sum += (sum >> 16);			/* add carry */
    696 	answer = ~sum;				/* truncate to 16 bits */
    697 	return(answer);
    698 }
    699 
    700 /*
    701  * tvsub --
    702  *	Subtract 2 timeval structs:  out = out - in.  Out is assumed to
    703  * be >= in.
    704  */
    705 void
    706 tvsub(out, in)
    707 	register struct timeval *out, *in;
    708 {
    709 	if ((out->tv_usec -= in->tv_usec) < 0) {
    710 		--out->tv_sec;
    711 		out->tv_usec += 1000000;
    712 	}
    713 	out->tv_sec -= in->tv_sec;
    714 }
    715 
    716 /*
    717  * finish --
    718  *	Print out statistics, and give up.
    719  */
    720 void
    721 finish()
    722 {
    723 	register int i;
    724 
    725 	(void)signal(SIGINT, SIG_IGN);
    726 	(void)putchar('\n');
    727 	(void)fflush(stdout);
    728 	(void)printf("--- %s ping statistics ---\n", hostname);
    729 	(void)printf("%ld packets transmitted, ", ntransmitted);
    730 	(void)printf("%ld packets received, ", nreceived);
    731 	if (nrepeats)
    732 		(void)printf("+%ld duplicates, ", nrepeats);
    733 	if (ntransmitted)
    734 		if (nreceived > ntransmitted)
    735 			(void)printf("-- somebody's printing up packets!");
    736 		else
    737 			(void)printf("%d%% packet loss",
    738 			    (int) (((ntransmitted - nreceived) * 100) /
    739 			    ntransmitted));
    740 	(void)putchar('\n');
    741 	if (nreceived && timing) {
    742 		/* Only display average to microseconds */
    743 		i = 1000.0 * tsum / (nreceived + nrepeats);
    744 		(void)printf("round-trip min/avg/max = %.3f/%.3f/%.3f ms\n",
    745 		    tmin, ((double)i) / 1000.0, tmax);
    746 	}
    747 	exit(0);
    748 }
    749 
    750 #ifdef notdef
    751 static char *ttab[] = {
    752 	"Echo Reply",		/* ip + seq + udata */
    753 	"Dest Unreachable",	/* net, host, proto, port, frag, sr + IP */
    754 	"Source Quench",	/* IP */
    755 	"Redirect",		/* redirect type, gateway, + IP  */
    756 	"Echo",
    757 	"Time Exceeded",	/* transit, frag reassem + IP */
    758 	"Parameter Problem",	/* pointer + IP */
    759 	"Timestamp",		/* id + seq + three timestamps */
    760 	"Timestamp Reply",	/* " */
    761 	"Info Request",		/* id + sq */
    762 	"Info Reply"		/* " */
    763 };
    764 #endif
    765 
    766 /*
    767  * pr_icmph --
    768  *	Print a descriptive string about an ICMP header.
    769  */
    770 void
    771 pr_icmph(icp)
    772 	struct icmp *icp;
    773 {
    774 	switch(icp->icmp_type) {
    775 	case ICMP_ECHOREPLY:
    776 		(void)printf("Echo Reply\n");
    777 		/* XXX ID + Seq + Data */
    778 		break;
    779 	case ICMP_UNREACH:
    780 		switch(icp->icmp_code) {
    781 		case ICMP_UNREACH_NET:
    782 			(void)printf("Destination Net Unreachable\n");
    783 			break;
    784 		case ICMP_UNREACH_HOST:
    785 			(void)printf("Destination Host Unreachable\n");
    786 			break;
    787 		case ICMP_UNREACH_PROTOCOL:
    788 			(void)printf("Destination Protocol Unreachable\n");
    789 			break;
    790 		case ICMP_UNREACH_PORT:
    791 			(void)printf("Destination Port Unreachable\n");
    792 			break;
    793 		case ICMP_UNREACH_NEEDFRAG:
    794 			(void)printf("frag needed and DF set\n");
    795 			break;
    796 		case ICMP_UNREACH_SRCFAIL:
    797 			(void)printf("Source Route Failed\n");
    798 			break;
    799 		default:
    800 			(void)printf("Dest Unreachable, Bad Code: %d\n",
    801 			    icp->icmp_code);
    802 			break;
    803 		}
    804 		/* Print returned IP header information */
    805 #ifndef icmp_data
    806 		pr_retip(&icp->icmp_ip);
    807 #else
    808 		pr_retip((struct ip *)icp->icmp_data);
    809 #endif
    810 		break;
    811 	case ICMP_SOURCEQUENCH:
    812 		(void)printf("Source Quench\n");
    813 #ifndef icmp_data
    814 		pr_retip(&icp->icmp_ip);
    815 #else
    816 		pr_retip((struct ip *)icp->icmp_data);
    817 #endif
    818 		break;
    819 	case ICMP_REDIRECT:
    820 		switch(icp->icmp_code) {
    821 		case ICMP_REDIRECT_NET:
    822 			(void)printf("Redirect Network");
    823 			break;
    824 		case ICMP_REDIRECT_HOST:
    825 			(void)printf("Redirect Host");
    826 			break;
    827 		case ICMP_REDIRECT_TOSNET:
    828 			(void)printf("Redirect Type of Service and Network");
    829 			break;
    830 		case ICMP_REDIRECT_TOSHOST:
    831 			(void)printf("Redirect Type of Service and Host");
    832 			break;
    833 		default:
    834 			(void)printf("Redirect, Bad Code: %d", icp->icmp_code);
    835 			break;
    836 		}
    837 		(void)printf("(New addr: 0x%08lx)\n", icp->icmp_gwaddr.s_addr);
    838 #ifndef icmp_data
    839 		pr_retip(&icp->icmp_ip);
    840 #else
    841 		pr_retip((struct ip *)icp->icmp_data);
    842 #endif
    843 		break;
    844 	case ICMP_ECHO:
    845 		(void)printf("Echo Request\n");
    846 		/* XXX ID + Seq + Data */
    847 		break;
    848 	case ICMP_TIMXCEED:
    849 		switch(icp->icmp_code) {
    850 		case ICMP_TIMXCEED_INTRANS:
    851 			(void)printf("Time to live exceeded\n");
    852 			break;
    853 		case ICMP_TIMXCEED_REASS:
    854 			(void)printf("Frag reassembly time exceeded\n");
    855 			break;
    856 		default:
    857 			(void)printf("Time exceeded, Bad Code: %d\n",
    858 			    icp->icmp_code);
    859 			break;
    860 		}
    861 #ifndef icmp_data
    862 		pr_retip(&icp->icmp_ip);
    863 #else
    864 		pr_retip((struct ip *)icp->icmp_data);
    865 #endif
    866 		break;
    867 	case ICMP_PARAMPROB:
    868 		(void)printf("Parameter problem: pointer = 0x%02x\n",
    869 		    icp->icmp_hun.ih_pptr);
    870 #ifndef icmp_data
    871 		pr_retip(&icp->icmp_ip);
    872 #else
    873 		pr_retip((struct ip *)icp->icmp_data);
    874 #endif
    875 		break;
    876 	case ICMP_TSTAMP:
    877 		(void)printf("Timestamp\n");
    878 		/* XXX ID + Seq + 3 timestamps */
    879 		break;
    880 	case ICMP_TSTAMPREPLY:
    881 		(void)printf("Timestamp Reply\n");
    882 		/* XXX ID + Seq + 3 timestamps */
    883 		break;
    884 	case ICMP_IREQ:
    885 		(void)printf("Information Request\n");
    886 		/* XXX ID + Seq */
    887 		break;
    888 	case ICMP_IREQREPLY:
    889 		(void)printf("Information Reply\n");
    890 		/* XXX ID + Seq */
    891 		break;
    892 #ifdef ICMP_MASKREQ
    893 	case ICMP_MASKREQ:
    894 		(void)printf("Address Mask Request\n");
    895 		break;
    896 #endif
    897 #ifdef ICMP_MASKREPLY
    898 	case ICMP_MASKREPLY:
    899 		(void)printf("Address Mask Reply\n");
    900 		break;
    901 #endif
    902 	default:
    903 		(void)printf("Bad ICMP type: %d\n", icp->icmp_type);
    904 	}
    905 }
    906 
    907 /*
    908  * pr_iph --
    909  *	Print an IP header with options.
    910  */
    911 void
    912 pr_iph(ip)
    913 	struct ip *ip;
    914 {
    915 	int hlen;
    916 	u_char *cp;
    917 
    918 	hlen = ip->ip_hl << 2;
    919 	cp = (u_char *)ip + 20;		/* point to options */
    920 
    921 	(void)printf("Vr HL TOS  Len   ID Flg  off TTL Pro  cks      Src      Dst Data\n");
    922 	(void)printf(" %1x  %1x  %02x %04x %04x",
    923 	    ip->ip_v, ip->ip_hl, ip->ip_tos, ip->ip_len, ip->ip_id);
    924 	(void)printf("   %1x %04x", ((ip->ip_off) & 0xe000) >> 13,
    925 	    (ip->ip_off) & 0x1fff);
    926 	(void)printf("  %02x  %02x %04x", ip->ip_ttl, ip->ip_p, ip->ip_sum);
    927 	(void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_src.s_addr));
    928 	(void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_dst.s_addr));
    929 	/* dump and option bytes */
    930 	while (hlen-- > 20) {
    931 		(void)printf("%02x", *cp++);
    932 	}
    933 	(void)putchar('\n');
    934 }
    935 
    936 /*
    937  * pr_addr --
    938  *	Return an ascii host address as a dotted quad and optionally with
    939  * a hostname.
    940  */
    941 char *
    942 pr_addr(l)
    943 	u_long l;
    944 {
    945 	struct hostent *hp;
    946 	static char buf[80];
    947 
    948 	if ((options & F_NUMERIC) ||
    949 	    !(hp = gethostbyaddr((char *)&l, 4, AF_INET)))
    950 		(void)sprintf(buf, "%s", inet_ntoa(*(struct in_addr *)&l));
    951 	else
    952 		(void)sprintf(buf, "%s (%s)", hp->h_name,
    953 		    inet_ntoa(*(struct in_addr *)&l));
    954 	return(buf);
    955 }
    956 
    957 /*
    958  * pr_retip --
    959  *	Dump some info on a returned (via ICMP) IP packet.
    960  */
    961 void
    962 pr_retip(ip)
    963 	struct ip *ip;
    964 {
    965 	int hlen;
    966 	u_char *cp;
    967 
    968 	pr_iph(ip);
    969 	hlen = ip->ip_hl << 2;
    970 	cp = (u_char *)ip + hlen;
    971 
    972 	if (ip->ip_p == 6)
    973 		(void)printf("TCP: from port %u, to port %u (decimal)\n",
    974 		    (*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3)));
    975 	else if (ip->ip_p == 17)
    976 		(void)printf("UDP: from port %u, to port %u (decimal)\n",
    977 			(*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3)));
    978 }
    979 
    980 void
    981 fill(bp, patp)
    982 	char *bp, *patp;
    983 {
    984 	register int ii, jj, kk;
    985 	int pat[16];
    986 	char *cp;
    987 
    988 	for (cp = patp; *cp; cp++)
    989 		if (!isxdigit(*cp))
    990 			errx(1, "patterns must be specified as hex digits");
    991 	ii = sscanf(patp,
    992 	    "%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x",
    993 	    &pat[0], &pat[1], &pat[2], &pat[3], &pat[4], &pat[5], &pat[6],
    994 	    &pat[7], &pat[8], &pat[9], &pat[10], &pat[11], &pat[12],
    995 	    &pat[13], &pat[14], &pat[15]);
    996 
    997 	if (ii > 0)
    998 		for (kk = 0;
    999 		    kk <= MAXPACKET - (8 + sizeof(struct timeval) + ii);
   1000 		    kk += ii)
   1001 			for (jj = 0; jj < ii; ++jj)
   1002 				bp[jj + kk] = pat[jj];
   1003 	if (!(options & F_QUIET)) {
   1004 		(void)printf("PATTERN: 0x");
   1005 		for (jj = 0; jj < ii; ++jj)
   1006 			(void)printf("%02x", bp[jj] & 0xFF);
   1007 		(void)printf("\n");
   1008 	}
   1009 }
   1010 
   1011 void
   1012 usage()
   1013 {
   1014 	(void)fprintf(stderr,
   1015 	    "usage: ping [-dfLnqRrv] [-c count] [-I ifaddr] [-i wait] [-l preload]\n\t[-p pattern] [-s packetsize] [-t ttl] host\n");
   1016 	exit(1);
   1017 }
   1018