Home | History | Annotate | Line # | Download | only in traceroute
traceroute.c revision 1.11
      1 /*	$NetBSD: traceroute.c,v 1.11 1996/06/30 22:51:11 jtc Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1990, 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  * Van Jacobson.
      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) 1990, 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[] = "@(#)traceroute.c	8.1 (Berkeley) 6/6/93";*/
     48 #else
     49 static char rcsid[] = "$NetBSD: traceroute.c,v 1.11 1996/06/30 22:51:11 jtc Exp $";
     50 #endif
     51 #endif /* not lint */
     52 
     53 /*
     54  * traceroute host  - trace the route ip packets follow going to "host".
     55  *
     56  * Attempt to trace the route an ip packet would follow to some
     57  * internet host.  We find out intermediate hops by launching probe
     58  * packets with a small ttl (time to live) then listening for an
     59  * icmp "time exceeded" reply from a gateway.  We start our probes
     60  * with a ttl of one and increase by one until we get an icmp "port
     61  * unreachable" (which means we got to "host") or hit a max (which
     62  * defaults to 30 hops & can be changed with the -m flag).  Three
     63  * probes (change with -q flag) are sent at each ttl setting and a
     64  * line is printed showing the ttl, address of the gateway and
     65  * round trip time of each probe.  If the probe answers come from
     66  * different gateways, the address of each responding system will
     67  * be printed.  If there is no response within a 5 sec. timeout
     68  * interval (changed with the -w flag), a "*" is printed for that
     69  * probe.
     70  *
     71  * Probe packets are UDP format.  We don't want the destination
     72  * host to process them so the destination port is set to an
     73  * unlikely value (if some clod on the destination is using that
     74  * value, it can be changed with the -p flag).
     75  *
     76  * A sample use might be:
     77  *
     78  *     [yak 71]% traceroute nis.nsf.net.
     79  *     traceroute to nis.nsf.net (35.1.1.48), 30 hops max, 56 byte packet
     80  *      1  helios.ee.lbl.gov (128.3.112.1)  19 ms  19 ms  0 ms
     81  *      2  lilac-dmc.Berkeley.EDU (128.32.216.1)  39 ms  39 ms  19 ms
     82  *      3  lilac-dmc.Berkeley.EDU (128.32.216.1)  39 ms  39 ms  19 ms
     83  *      4  ccngw-ner-cc.Berkeley.EDU (128.32.136.23)  39 ms  40 ms  39 ms
     84  *      5  ccn-nerif22.Berkeley.EDU (128.32.168.22)  39 ms  39 ms  39 ms
     85  *      6  128.32.197.4 (128.32.197.4)  40 ms  59 ms  59 ms
     86  *      7  131.119.2.5 (131.119.2.5)  59 ms  59 ms  59 ms
     87  *      8  129.140.70.13 (129.140.70.13)  99 ms  99 ms  80 ms
     88  *      9  129.140.71.6 (129.140.71.6)  139 ms  239 ms  319 ms
     89  *     10  129.140.81.7 (129.140.81.7)  220 ms  199 ms  199 ms
     90  *     11  nic.merit.edu (35.1.1.48)  239 ms  239 ms  239 ms
     91  *
     92  * Note that lines 2 & 3 are the same.  This is due to a buggy
     93  * kernel on the 2nd hop system -- lbl-csam.arpa -- that forwards
     94  * packets with a zero ttl.
     95  *
     96  * A more interesting example is:
     97  *
     98  *     [yak 72]% traceroute allspice.lcs.mit.edu.
     99  *     traceroute to allspice.lcs.mit.edu (18.26.0.115), 30 hops max
    100  *      1  helios.ee.lbl.gov (128.3.112.1)  0 ms  0 ms  0 ms
    101  *      2  lilac-dmc.Berkeley.EDU (128.32.216.1)  19 ms  19 ms  19 ms
    102  *      3  lilac-dmc.Berkeley.EDU (128.32.216.1)  39 ms  19 ms  19 ms
    103  *      4  ccngw-ner-cc.Berkeley.EDU (128.32.136.23)  19 ms  39 ms  39 ms
    104  *      5  ccn-nerif22.Berkeley.EDU (128.32.168.22)  20 ms  39 ms  39 ms
    105  *      6  128.32.197.4 (128.32.197.4)  59 ms  119 ms  39 ms
    106  *      7  131.119.2.5 (131.119.2.5)  59 ms  59 ms  39 ms
    107  *      8  129.140.70.13 (129.140.70.13)  80 ms  79 ms  99 ms
    108  *      9  129.140.71.6 (129.140.71.6)  139 ms  139 ms  159 ms
    109  *     10  129.140.81.7 (129.140.81.7)  199 ms  180 ms  300 ms
    110  *     11  129.140.72.17 (129.140.72.17)  300 ms  239 ms  239 ms
    111  *     12  * * *
    112  *     13  128.121.54.72 (128.121.54.72)  259 ms  499 ms  279 ms
    113  *     14  * * *
    114  *     15  * * *
    115  *     16  * * *
    116  *     17  * * *
    117  *     18  ALLSPICE.LCS.MIT.EDU (18.26.0.115)  339 ms  279 ms  279 ms
    118  *
    119  * (I start to see why I'm having so much trouble with mail to
    120  * MIT.)  Note that the gateways 12, 14, 15, 16 & 17 hops away
    121  * either don't send ICMP "time exceeded" messages or send them
    122  * with a ttl too small to reach us.  14 - 17 are running the
    123  * MIT C Gateway code that doesn't send "time exceeded"s.  God
    124  * only knows what's going on with 12.
    125  *
    126  * The silent gateway 12 in the above may be the result of a bug in
    127  * the 4.[23]BSD network code (and its derivatives):  4.x (x <= 3)
    128  * sends an unreachable message using whatever ttl remains in the
    129  * original datagram.  Since, for gateways, the remaining ttl is
    130  * zero, the icmp "time exceeded" is guaranteed to not make it back
    131  * to us.  The behavior of this bug is slightly more interesting
    132  * when it appears on the destination system:
    133  *
    134  *      1  helios.ee.lbl.gov (128.3.112.1)  0 ms  0 ms  0 ms
    135  *      2  lilac-dmc.Berkeley.EDU (128.32.216.1)  39 ms  19 ms  39 ms
    136  *      3  lilac-dmc.Berkeley.EDU (128.32.216.1)  19 ms  39 ms  19 ms
    137  *      4  ccngw-ner-cc.Berkeley.EDU (128.32.136.23)  39 ms  40 ms  19 ms
    138  *      5  ccn-nerif35.Berkeley.EDU (128.32.168.35)  39 ms  39 ms  39 ms
    139  *      6  csgw.Berkeley.EDU (128.32.133.254)  39 ms  59 ms  39 ms
    140  *      7  * * *
    141  *      8  * * *
    142  *      9  * * *
    143  *     10  * * *
    144  *     11  * * *
    145  *     12  * * *
    146  *     13  rip.Berkeley.EDU (128.32.131.22)  59 ms !  39 ms !  39 ms !
    147  *
    148  * Notice that there are 12 "gateways" (13 is the final
    149  * destination) and exactly the last half of them are "missing".
    150  * What's really happening is that rip (a Sun-3 running Sun OS3.5)
    151  * is using the ttl from our arriving datagram as the ttl in its
    152  * icmp reply.  So, the reply will time out on the return path
    153  * (with no notice sent to anyone since icmp's aren't sent for
    154  * icmp's) until we probe with a ttl that's at least twice the path
    155  * length.  I.e., rip is really only 7 hops away.  A reply that
    156  * returns with a ttl of 1 is a clue this problem exists.
    157  * Traceroute prints a "!" after the time if the ttl is <= 1.
    158  * Since vendors ship a lot of obsolete (DEC's Ultrix, Sun 3.x) or
    159  * non-standard (HPUX) software, expect to see this problem
    160  * frequently and/or take care picking the target host of your
    161  * probes.
    162  *
    163  * Other possible annotations after the time are !H, !N, !P (got a host,
    164  * network or protocol unreachable, respectively), !S or !F (source
    165  * route failed or fragmentation needed -- neither of these should
    166  * ever occur and the associated gateway is busted if you see one).  If
    167  * almost all the probes result in some kind of unreachable, traceroute
    168  * will give up and exit.
    169  *
    170  * Notes
    171  * -----
    172  * This program must be run by root or be setuid.  (I suggest that
    173  * you *don't* make it setuid -- casual use could result in a lot
    174  * of unnecessary traffic on our poor, congested nets.)
    175  *
    176  * This program requires a kernel mod that does not appear in any
    177  * system available from Berkeley:  A raw ip socket using proto
    178  * IPPROTO_RAW must interpret the data sent as an ip datagram (as
    179  * opposed to data to be wrapped in a ip datagram).  See the README
    180  * file that came with the source to this program for a description
    181  * of the mods I made to /sys/netinet/raw_ip.c.  Your mileage may
    182  * vary.  But, again, ANY 4.x (x < 4) BSD KERNEL WILL HAVE TO BE
    183  * MODIFIED TO RUN THIS PROGRAM.
    184  *
    185  * The udp port usage may appear bizarre (well, ok, it is bizarre).
    186  * The problem is that an icmp message only contains 8 bytes of
    187  * data from the original datagram.  8 bytes is the size of a udp
    188  * header so, if we want to associate replies with the original
    189  * datagram, the necessary information must be encoded into the
    190  * udp header (the ip id could be used but there's no way to
    191  * interlock with the kernel's assignment of ip id's and, anyway,
    192  * it would have taken a lot more kernel hacking to allow this
    193  * code to set the ip id).  So, to allow two or more users to
    194  * use traceroute simultaneously, we use this task's pid as the
    195  * source port (the high bit is set to move the port number out
    196  * of the "likely" range).  To keep track of which probe is being
    197  * replied to (so times and/or hop counts don't get confused by a
    198  * reply that was delayed in transit), we increment the destination
    199  * port number before each probe.
    200  *
    201  * Don't use this as a coding example.  I was trying to find a
    202  * routing problem and this code sort-of popped out after 48 hours
    203  * without sleep.  I was amazed it ever compiled, much less ran.
    204  *
    205  * I stole the idea for this program from Steve Deering.  Since
    206  * the first release, I've learned that had I attended the right
    207  * IETF working group meetings, I also could have stolen it from Guy
    208  * Almes or Matt Mathis.  I don't know (or care) who came up with
    209  * the idea first.  I envy the originators' perspicacity and I'm
    210  * glad they didn't keep the idea a secret.
    211  *
    212  * Tim Seaver, Ken Adelman and C. Philip Wood provided bug fixes and/or
    213  * enhancements to the original distribution.
    214  *
    215  * I've hacked up a round-trip-route version of this that works by
    216  * sending a loose-source-routed udp datagram through the destination
    217  * back to yourself.  Unfortunately, SO many gateways botch source
    218  * routing, the thing is almost worthless.  Maybe one day...
    219  *
    220  *  -- Van Jacobson (van (at) helios.ee.lbl.gov)
    221  *     Tue Dec 20 03:50:13 PST 1988
    222  */
    223 
    224 #include <sys/param.h>
    225 #include <sys/time.h>
    226 #include <sys/socket.h>
    227 #include <sys/file.h>
    228 #include <sys/ioctl.h>
    229 
    230 #include <netinet/in_systm.h>
    231 #include <netinet/in.h>
    232 #include <netinet/ip.h>
    233 #include <netinet/ip_icmp.h>
    234 #include <netinet/ip_var.h>
    235 #include <netinet/udp.h>
    236 
    237 #include <arpa/inet.h>
    238 
    239 #include <ctype.h>
    240 #include <err.h>
    241 #include <errno.h>
    242 #include <netdb.h>
    243 #include <stdio.h>
    244 #include <stdlib.h>
    245 #include <string.h>
    246 #include <unistd.h>
    247 
    248 #define Fprintf (void)fprintf
    249 #define Sprintf (void)sprintf
    250 #define Printf (void)printf
    251 
    252 #define	HEADERSIZE	(sizeof(struct ip) + lsrrlen + sizeof(struct udphdr) + sizeof(struct packetdata))
    253 #define	MAX_LSRR	((MAX_IPOPTLEN - 4) / 4)
    254 
    255 /*
    256  * Format of the data in a (udp) probe packet.
    257  */
    258 struct packetdata {
    259 	u_char seq;		/* sequence number of this packet */
    260 	u_char ttl;		/* ttl packet left with */
    261 	struct timeval tv;	/* time packet left */
    262 };
    263 
    264 struct in_addr gateway[MAX_LSRR + 1];
    265 int lsrrlen = 0;
    266 
    267 u_char packet[512], *outpacket;	/* last inbound (icmp) packet */
    268 
    269 int wait_for_reply __P((int, struct sockaddr_in *));
    270 void send_probe __P((int, int, struct sockaddr_in *));
    271 double deltaT __P((struct timeval *, struct timeval *));
    272 int packet_ok __P((u_char *, int, struct sockaddr_in *, int));
    273 void print __P((u_char *, int, struct sockaddr_in *));
    274 char *inetname __P((struct in_addr));
    275 void usage __P((void));
    276 
    277 int s;				/* receive (icmp) socket file descriptor */
    278 int sndsock;			/* send (udp) socket file descriptor */
    279 struct timezone tz;		/* leftover */
    280 
    281 int datalen;			/* How much data */
    282 
    283 char *source = 0;
    284 char *hostname;
    285 
    286 int nprobes = 3;
    287 int max_ttl = 30;
    288 u_short ident;
    289 u_short port = 32768+666;	/* start udp dest port # for probe packets */
    290 int options;			/* socket options */
    291 int verbose;
    292 int waittime = 5;		/* time to wait for response (in seconds) */
    293 int nflag;			/* print addresses numerically */
    294 int dump;
    295 
    296 int
    297 main(argc, argv)
    298 	int argc;
    299 	char *argv[];
    300 {
    301 	struct hostent *hp;
    302 	struct protoent *pe;
    303 	struct sockaddr_in from, to;
    304 	int ch, i, lsrr, on, probe, seq, tos, ttl;
    305 	struct ip *ip;
    306 
    307 	lsrr = 0;
    308 	on = 1;
    309 	seq = tos = 0;
    310 	while ((ch = getopt(argc, argv, "dDg:m:np:q:rs:t:w:v")) != -1)
    311 		switch (ch) {
    312 		case 'd':
    313 			options |= SO_DEBUG;
    314 			break;
    315 		case 'D':
    316 			dump = 1;
    317 			break;
    318 		case 'g':
    319 			if (lsrr >= MAX_LSRR)
    320 				errx(1, "too many gateways; max %d", MAX_LSRR);
    321 			if (inet_aton(optarg, &gateway[lsrr]) == 0) {
    322 				hp = gethostbyname(optarg);
    323 				if (hp == 0)
    324 					errx(1, "unknown host %s", optarg);
    325 				memcpy(&gateway[lsrr], hp->h_addr, hp->h_length);
    326 			}
    327 			if (++lsrr == 1)
    328 				lsrrlen = 4;
    329 			lsrrlen += 4;
    330 			break;
    331 		case 'm':
    332 			max_ttl = atoi(optarg);
    333 			if (max_ttl < 1 || max_ttl > MAXTTL)
    334 				errx(1, "max ttl must be 1 to %d.", MAXTTL);
    335 			break;
    336 		case 'n':
    337 			nflag++;
    338 			break;
    339 		case 'p':
    340 			port = atoi(optarg);
    341 			if (port < 1)
    342 				errx(1, "port must be >0.");
    343 			break;
    344 		case 'q':
    345 			nprobes = atoi(optarg);
    346 			if (nprobes < 1)
    347 				errx(1, "nprobes must be >0.");
    348 			break;
    349 		case 'r':
    350 			options |= SO_DONTROUTE;
    351 			break;
    352 		case 's':
    353 			/*
    354 			 * set the ip source address of the outbound
    355 			 * probe (e.g., on a multi-homed host).
    356 			 */
    357 			source = optarg;
    358 			break;
    359 		case 't':
    360 			tos = atoi(optarg);
    361 			if (tos < 0 || tos > 255)
    362 				errx(1, "tos must be 0 to 255.");
    363 			break;
    364 		case 'v':
    365 			verbose++;
    366 			break;
    367 		case 'w':
    368 			waittime = atoi(optarg);
    369 			if (waittime <= 1)
    370 				errx(1, "wait must be >1 sec.");
    371 			break;
    372 		default:
    373 			usage();
    374 		}
    375 	argc -= optind;
    376 	argv += optind;
    377 
    378 	if (argc < 1)
    379 		usage();
    380 
    381 	setlinebuf (stdout);
    382 
    383 	(void) memset(&to, 0, sizeof(struct sockaddr));
    384 	to.sin_family = AF_INET;
    385 	if (inet_aton(*argv, &to.sin_addr) != 0)
    386 		hostname = *argv;
    387 	else {
    388 		hp = gethostbyname(*argv);
    389 		if (hp == 0)
    390 			errx(1, "unknown host %s", *argv);
    391 		to.sin_family = hp->h_addrtype;
    392 		memcpy(&to.sin_addr, hp->h_addr, hp->h_length);
    393 		hostname = hp->h_name;
    394 	}
    395 	if (*++argv)
    396 		datalen = atoi(*argv);
    397 	if (datalen < 0 || datalen > IP_MAXPACKET - HEADERSIZE)
    398 		errx(1, "packet size must be 0 to %d.",
    399 		    IP_MAXPACKET - HEADERSIZE);
    400 	datalen += HEADERSIZE;
    401 
    402 	outpacket = (u_char *)malloc(datalen);
    403 	if (outpacket == 0)
    404 		err(1, "malloc");
    405 	(void) memset(outpacket, 0, datalen);
    406 
    407 	ip = (struct ip *)outpacket;
    408 	if (lsrr != 0) {
    409 		u_char *p;
    410 		p = (u_char *)(ip + 1);
    411 		*p++ = IPOPT_NOP;
    412 		*p++ = IPOPT_LSRR;
    413 		*p++ = lsrrlen - 1;
    414 		*p++ = IPOPT_MINOFF;
    415 		gateway[lsrr] = to.sin_addr;
    416 		for (i = 1; i <= lsrr; i++)
    417 			*((struct in_addr *)p)++ = gateway[i];
    418 		ip->ip_dst = gateway[0];
    419 	} else
    420 		ip->ip_dst = to.sin_addr;
    421 	ip->ip_off = 0;
    422 	ip->ip_hl = (sizeof(struct ip) + lsrrlen) >> 2;
    423 	ip->ip_p = IPPROTO_UDP;
    424 	ip->ip_v = IPVERSION;
    425 	ip->ip_tos = tos;
    426 
    427 	ident = (getpid() & 0xffff) | 0x8000;
    428 
    429 	if ((pe = getprotobyname("icmp")) == NULL) {
    430 		Fprintf(stderr, "icmp: unknown protocol\n");
    431 		exit(10);
    432 	}
    433 	if ((s = socket(AF_INET, SOCK_RAW, pe->p_proto)) < 0)
    434 		err(5, "icmp socket");
    435 	if (options & SO_DEBUG)
    436 		(void) setsockopt(s, SOL_SOCKET, SO_DEBUG,
    437 				  (char *)&on, sizeof(on));
    438 	if (options & SO_DONTROUTE)
    439 		(void) setsockopt(s, SOL_SOCKET, SO_DONTROUTE,
    440 				  (char *)&on, sizeof(on));
    441 
    442 	if ((sndsock = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) < 0)
    443 		err(5, "raw socket");
    444 
    445 #ifdef SO_SNDBUF
    446 	if (setsockopt(sndsock, SOL_SOCKET, SO_SNDBUF, (char *)&datalen,
    447 		       sizeof(datalen)) < 0)
    448 		err(6, "SO_SNDBUF");
    449 #endif SO_SNDBUF
    450 #ifdef IP_HDRINCL
    451 	if (setsockopt(sndsock, IPPROTO_IP, IP_HDRINCL, (char *)&on,
    452 		       sizeof(on)) < 0)
    453 		err(6, "IP_HDRINCL");
    454 #endif IP_HDRINCL
    455 	if (options & SO_DEBUG)
    456 		(void) setsockopt(sndsock, SOL_SOCKET, SO_DEBUG,
    457 				  (char *)&on, sizeof(on));
    458 	if (options & SO_DONTROUTE)
    459 		(void) setsockopt(sndsock, SOL_SOCKET, SO_DONTROUTE,
    460 				  (char *)&on, sizeof(on));
    461 
    462 	if (source) {
    463 		(void) memset(&from, 0, sizeof(struct sockaddr));
    464 		from.sin_family = AF_INET;
    465 		if (inet_aton(source, &from.sin_addr) == 0)
    466 			errx(1, "unknown host %s", source);
    467 		ip->ip_src = from.sin_addr;
    468 #ifndef IP_HDRINCL
    469 		if (bind(sndsock, (struct sockaddr *)&from, sizeof(from)) < 0)
    470 			err(1, "bind");
    471 #endif IP_HDRINCL
    472 	}
    473 
    474 	Fprintf(stderr, "traceroute to %s (%s)", hostname,
    475 		inet_ntoa(to.sin_addr));
    476 	if (source)
    477 		Fprintf(stderr, " from %s", source);
    478 	Fprintf(stderr, ", %d hops max, %d byte packets\n", max_ttl, datalen);
    479 	(void) fflush(stderr);
    480 
    481 	for (ttl = 1; ttl <= max_ttl; ++ttl) {
    482 		u_long lastaddr = 0;
    483 		int got_there = 0;
    484 		int unreachable = 0;
    485 
    486 		Printf("%2d ", ttl);
    487 		for (probe = 0; probe < nprobes; ++probe) {
    488 			int cc;
    489 			struct timeval t1, t2;
    490 			struct timezone tz;
    491 
    492 			(void) gettimeofday(&t1, &tz);
    493 			send_probe(++seq, ttl, &to);
    494 			while (cc = wait_for_reply(s, &from)) {
    495 				(void) gettimeofday(&t2, &tz);
    496 				if ((i = packet_ok(packet, cc, &from, seq))) {
    497 					if (from.sin_addr.s_addr != lastaddr) {
    498 						print(packet, cc, &from);
    499 						lastaddr = from.sin_addr.s_addr;
    500 					}
    501 					Printf("  %g ms", deltaT(&t1, &t2));
    502 					switch(i - 1) {
    503 					case ICMP_UNREACH_PORT:
    504 #ifndef ARCHAIC
    505 						ip = (struct ip *)packet;
    506 						if (ip->ip_ttl <= 1)
    507 							Printf(" !");
    508 #endif ARCHAIC
    509 						++got_there;
    510 						break;
    511 					case ICMP_UNREACH_NET:
    512 						++unreachable;
    513 						Printf(" !N");
    514 						break;
    515 					case ICMP_UNREACH_HOST:
    516 						++unreachable;
    517 						Printf(" !H");
    518 						break;
    519 					case ICMP_UNREACH_PROTOCOL:
    520 						++got_there;
    521 						Printf(" !P");
    522 						break;
    523 					case ICMP_UNREACH_NEEDFRAG:
    524 						++unreachable;
    525 						Printf(" !F");
    526 						break;
    527 					case ICMP_UNREACH_SRCFAIL:
    528 						++unreachable;
    529 						Printf(" !S");
    530 						break;
    531 					}
    532 					break;
    533 				}
    534 			}
    535 			if (cc == 0)
    536 				Printf(" *");
    537 			(void) fflush(stdout);
    538 		}
    539 		putchar('\n');
    540 		if (got_there || unreachable >= nprobes)
    541 			exit(0);
    542 	}
    543 }
    544 
    545 int
    546 wait_for_reply(sock, from)
    547 	int sock;
    548 	struct sockaddr_in *from;
    549 {
    550 	fd_set fds;
    551 	struct timeval wait;
    552 	int cc = 0;
    553 	int fromlen = sizeof (*from);
    554 
    555 	FD_ZERO(&fds);
    556 	FD_SET(sock, &fds);
    557 	wait.tv_sec = waittime; wait.tv_usec = 0;
    558 
    559 	if (select(sock+1, &fds, (fd_set *)0, (fd_set *)0, &wait) > 0)
    560 		cc=recvfrom(s, (char *)packet, sizeof(packet), 0,
    561 			    (struct sockaddr *)from, &fromlen);
    562 
    563 	return(cc);
    564 }
    565 
    566 void
    567 dump_packet()
    568 {
    569 	u_char *p;
    570 	int i;
    571 
    572 	Fprintf(stderr, "packet data:");
    573 	for (p = outpacket, i = 0; i < datalen; i++) {
    574 		if ((i % 24) == 0)
    575 			Fprintf(stderr, "\n ");
    576 		Fprintf(stderr, " %02x", *p++);
    577 	}
    578 	Fprintf(stderr, "\n");
    579 }
    580 
    581 void
    582 send_probe(seq, ttl, to)
    583 	int seq, ttl;
    584 	struct sockaddr_in *to;
    585 {
    586 	struct ip *ip = (struct ip *)outpacket;
    587 	u_char *p = (u_char *)(ip + 1);
    588 	struct udphdr *up = (struct udphdr *)(p + lsrrlen);
    589 	struct packetdata *op = (struct packetdata *)(up + 1);
    590 	int i;
    591 
    592 	ip->ip_len = datalen;
    593 	ip->ip_ttl = ttl;
    594 	ip->ip_id = htons(ident+seq);
    595 
    596 	up->uh_sport = htons(ident);
    597 	up->uh_dport = htons(port+seq);
    598 	up->uh_ulen = htons((u_short)(datalen - sizeof(struct ip) - lsrrlen));
    599 	up->uh_sum = 0;
    600 
    601 	op->seq = seq;
    602 	op->ttl = ttl;
    603 	(void) gettimeofday(&op->tv, &tz);
    604 
    605 	if (dump)
    606 		dump_packet();
    607 
    608 	i = sendto(sndsock, outpacket, datalen, 0, (struct sockaddr *)to,
    609 		   sizeof(struct sockaddr_in));
    610 	if (i < 0 || i != datalen)  {
    611 		if (i<0)
    612 			perror("sendto");
    613 		Printf("traceroute: wrote %s %d chars, ret=%d\n", hostname,
    614 			datalen, i);
    615 		(void) fflush(stdout);
    616 	}
    617 }
    618 
    619 
    620 double
    621 deltaT(t1p, t2p)
    622 	struct timeval *t1p, *t2p;
    623 {
    624 	register double dt;
    625 
    626 	dt = (double)(t2p->tv_sec - t1p->tv_sec) * 1000.0 +
    627 	     (double)(t2p->tv_usec - t1p->tv_usec) / 1000.0;
    628 	return (dt);
    629 }
    630 
    631 
    632 /*
    633  * Convert an ICMP "type" field to a printable string.
    634  */
    635 char *
    636 pr_type(t)
    637 	u_char t;
    638 {
    639 	static char *ttab[] = {
    640 	"Echo Reply",	"ICMP 1",	"ICMP 2",	"Dest Unreachable",
    641 	"Source Quench", "Redirect",	"ICMP 6",	"ICMP 7",
    642 	"Echo",		"ICMP 9",	"ICMP 10",	"Time Exceeded",
    643 	"Param Problem", "Timestamp",	"Timestamp Reply", "Info Request",
    644 	"Info Reply"
    645 	};
    646 
    647 	if(t > 16)
    648 		return("OUT-OF-RANGE");
    649 
    650 	return(ttab[t]);
    651 }
    652 
    653 
    654 int
    655 packet_ok(buf, cc, from, seq)
    656 	u_char *buf;
    657 	int cc;
    658 	struct sockaddr_in *from;
    659 	int seq;
    660 {
    661 	register struct icmp *icp;
    662 	u_char type, code;
    663 	int hlen;
    664 #ifndef ARCHAIC
    665 	struct ip *ip;
    666 
    667 	ip = (struct ip *) buf;
    668 	hlen = ip->ip_hl << 2;
    669 	if (cc < hlen + ICMP_MINLEN) {
    670 		if (verbose)
    671 			Printf("packet too short (%d bytes) from %s\n", cc,
    672 				inet_ntoa(from->sin_addr));
    673 		return (0);
    674 	}
    675 	cc -= hlen;
    676 	icp = (struct icmp *)(buf + hlen);
    677 #else
    678 	icp = (struct icmp *)buf;
    679 #endif ARCHAIC
    680 	type = icp->icmp_type; code = icp->icmp_code;
    681 	if ((type == ICMP_TIMXCEED && code == ICMP_TIMXCEED_INTRANS) ||
    682 	    type == ICMP_UNREACH) {
    683 		struct ip *hip;
    684 		struct udphdr *up;
    685 
    686 		hip = &icp->icmp_ip;
    687 		hlen = hip->ip_hl << 2;
    688 		up = (struct udphdr *)((u_char *)hip + hlen);
    689 		if (hlen + 12 <= cc && hip->ip_p == IPPROTO_UDP &&
    690 		    up->uh_sport == htons(ident) &&
    691 		    up->uh_dport == htons(port+seq))
    692 			return (type == ICMP_TIMXCEED? -1 : code+1);
    693 	}
    694 #ifndef ARCHAIC
    695 	if (verbose) {
    696 		int i;
    697 		u_long *lp = (u_long *)&icp->icmp_ip;
    698 
    699 		Printf("\n%d bytes from %s to %s", cc,
    700 			inet_ntoa(from->sin_addr), inet_ntoa(ip->ip_dst));
    701 		Printf(": icmp type %d (%s) code %d\n", type, pr_type(type),
    702 		       icp->icmp_code);
    703 		for (i = 4; i < cc ; i += sizeof(long))
    704 			Printf("%2d: x%8.8lx\n", i, *lp++);
    705 	}
    706 #endif ARCHAIC
    707 	return(0);
    708 }
    709 
    710 
    711 void
    712 print(buf, cc, from)
    713 	u_char *buf;
    714 	int cc;
    715 	struct sockaddr_in *from;
    716 {
    717 	struct ip *ip;
    718 	int hlen;
    719 
    720 	ip = (struct ip *) buf;
    721 	hlen = ip->ip_hl << 2;
    722 	cc -= hlen;
    723 
    724 	if (nflag)
    725 		Printf(" %s", inet_ntoa(from->sin_addr));
    726 	else
    727 		Printf(" %s (%s)", inetname(from->sin_addr),
    728 		       inet_ntoa(from->sin_addr));
    729 
    730 	if (verbose)
    731 		Printf (" %d bytes to %s", cc, inet_ntoa (ip->ip_dst));
    732 }
    733 
    734 
    735 #ifdef notyet
    736 /*
    737  * Checksum routine for Internet Protocol family headers (C Version)
    738  */
    739 u_short
    740 in_cksum(addr, len)
    741 	u_short *addr;
    742 	int len;
    743 {
    744 	register int nleft = len;
    745 	register u_short *w = addr;
    746 	register u_short answer;
    747 	register int sum = 0;
    748 
    749 	/*
    750 	 *  Our algorithm is simple, using a 32 bit accumulator (sum),
    751 	 *  we add sequential 16 bit words to it, and at the end, fold
    752 	 *  back all the carry bits from the top 16 bits into the lower
    753 	 *  16 bits.
    754 	 */
    755 	while (nleft > 1)  {
    756 		sum += *w++;
    757 		nleft -= 2;
    758 	}
    759 
    760 	/* mop up an odd byte, if necessary */
    761 	if (nleft == 1)
    762 		sum += *(u_char *)w;
    763 
    764 	/*
    765 	 * add back carry outs from top 16 bits to low 16 bits
    766 	 */
    767 	sum = (sum >> 16) + (sum & 0xffff);	/* add hi 16 to low 16 */
    768 	sum += (sum >> 16);			/* add carry */
    769 	answer = ~sum;				/* truncate to 16 bits */
    770 	return (answer);
    771 }
    772 #endif notyet
    773 
    774 /*
    775  * Construct an Internet address representation.
    776  * If the nflag has been supplied, give
    777  * numeric value, otherwise try for symbolic name.
    778  */
    779 char *
    780 inetname(in)
    781 	struct in_addr in;
    782 {
    783 	register char *cp;
    784 	static char line[50];
    785 	struct hostent *hp;
    786 	static char domain[MAXHOSTNAMELEN + 1];
    787 	static int first = 1;
    788 
    789 	if (first && !nflag) {
    790 		first = 0;
    791 		if (gethostname(domain, MAXHOSTNAMELEN) == 0 &&
    792 		    (cp = index(domain, '.')))
    793 			(void) strcpy(domain, cp + 1);
    794 		else
    795 			domain[0] = 0;
    796 	}
    797 	cp = 0;
    798 	if (!nflag && in.s_addr != INADDR_ANY) {
    799 		hp = gethostbyaddr((char *)&in, sizeof (in), AF_INET);
    800 		if (hp) {
    801 			if ((cp = index(hp->h_name, '.')) &&
    802 			    !strcmp(cp + 1, domain))
    803 				*cp = 0;
    804 			cp = hp->h_name;
    805 		}
    806 	}
    807 	if (cp)
    808 		(void) strcpy(line, cp);
    809 	else {
    810 		in.s_addr = ntohl(in.s_addr);
    811 #define C(x)	((x) & 0xff)
    812 		Sprintf(line, "%lu.%lu.%lu.%lu", C(in.s_addr >> 24),
    813 			C(in.s_addr >> 16), C(in.s_addr >> 8), C(in.s_addr));
    814 	}
    815 	return (line);
    816 }
    817 
    818 void
    819 usage()
    820 {
    821 	(void)fprintf(stderr,
    822 "usage: traceroute [-dDnrv] [-g gateway_addr] ... [-m max_ttl] [-p port#]\n\t\
    823 [-q nqueries] [-s src_addr] [-t tos] [-w wait] host [data size]\n");
    824 	exit(1);
    825 }
    826