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