traceroute for 2.10.1BSD

Steven M. SchultzY sms at wlv.imsd.contel.com
Thu May 25 03:11:16 AEST 1989


	Traceroute for 2.10.1BSD may be had by installing the replacement
	netinet/raw_ip.c attached to this README file.  Works fine!

	The TTL bug that is mentioned in the README had already been
	fixed in 2.10.1BSD so you don't have to worry about it.

	The Makefile doesn't grok the new man page system - you'll
	have to:
		"nroff -man traceroute.8 >/usr/man/cat8/traceroute.0
		"chmod 0444 /usr/man/cat8/traceroute.0"

	Steven M. Schultz
	sms at wlv.imsd.contel.com

--------------------------cut here---------------------
#! /bin/sh
# This is a shell archive, meaning:
# 1. Remove everything above the #! /bin/sh line.
# 2. Save the resulting text in a file.
# 3. Execute the file with /bin/sh (not csh) to create:
#	README
#	Makefile
#	traceroute.8
#	traceroute.c
#	mean.awk
#	median.awk
# This archive created: Wed May 24 10:06:37 1989
export PATH; PATH=/bin:/usr/bin:$PATH
if test -f 'README'
then
	echo shar: "will not over-write existing file 'README'"
else
sed 's/^X//' << \SHAR_EOF > 'README'
XVan Jacobson (van at helios.ee.lbl.gov)
XTue Dec 27 06:24:24 PST 1988
X
XTraceroute is a system administrators utility to trace the route
Xip packets from the current system take in getting to some
Xdestination system.  See the comments at the front of the
Xprogram for a description of its use.
X
XThis program 
X
X a) can only be run by root (it uses raw ip sockets).
X
X b) REQUIRES A KERNEL MOD to the raw ip output code to run.
X
XIf you want to hack on your kernel, my modified version of the
Xroutine rip_output (in file /sys/netinet/raw_ip.c) is attached.
XThis code may or may not resemble the code in your kernel.
XIt may offer you a place to start but I make no promises.
XIf you do hack your kernel, remember to test everything that uses
Xraw ip sockets (e.g., ping and egpup/gated) & make sure they still
Xwork.  I wish you the best of luck and you're on your own.
X
XIf your system has the ttl bug mentioned in the source, you
Xmight want to fix it while you're in the kernel.  (This bug
Xappears in all releases of BSD up to but not including 4.3tahoe.
XIf your version of netinet/ip_icmp.c is any earlier than 7.3
X(April, '87), it has the bug.)  The fix is just to add the line
X	ip->ip_ttl = MAXTTL;
Xafter the line
X	ip->ip_src = t;
X(or anywhere before the call to icmp_send) in routine icmp_reflect.
X
XIf you're running this on a pre-4.3bsd system (e.g., Sun 3.x,
XUltrix) that strips ip headers from icmp messages, add -DARCHAIC
Xto CFLAGS in the Makefile.  Also note that rip_output contains
Xa conditional for a 4.2/4.3 change in the location of a raw
Xsocket's protocol number.  I've checked this under 4.3 & Sun OS
X3.5 but you should double-check your system to make sure the
Xappropriate branch of the #if is taken (check the line that
Xassigned to ip->ip_p in your system's original rip_output).
X
XA couple of awk programs to massage the traceroute output are
Xincluded.  "mean.awk" and "median.awk" compute the mean and median
Xtime to each hop, respectively.  I've found that something like
X
X	traceroute -q 7 foo.somewhere >t
X	awk -f median.awk t | graph
X
Xcan give you a quick picture of the bad spots on a long
Xpath (median is usually a better noise filter than mean).
X
XEnjoy.
X
X - Van Jacobson (van at helios.ee.lbl.gov)
X
X=================replacement netinet/raw_ip.c for 2.10.1BSD====================
X===== rather than the 'diff' that was originally at this point, here is
X===== a replacement raw_ip.c, the sum total difference between this
X===== module and the one from a 4.3BSD system (after applying the diff)
X===== is 1 line: the #include "domain.h"
X
X/*
X * Copyright (c) 1982, 1986 Regents of the University of California.
X * All rights reserved.
X *
X * Redistribution and use in source and binary forms are permitted
X * provided that this notice is preserved and that due credit is given
X * to the University of California at Berkeley. The name of the University
X * may not be used to endorse or promote products derived from this
X * software without specific prior written permission. This software
X * is provided ``as is'' without express or implied warranty.
X *
X *	@(#)raw_ip.c	7.3 (Berkeley) 12/7/87
X */
X
X#include "param.h"
X#include "mbuf.h"
X#include "socket.h"
X#include "protosw.h"
X#include "socketvar.h"
X#include "errno.h"
X
X#include "../net/if.h"
X#include "../net/route.h"
X#include "../net/raw_cb.h"
X
X#include "domain.h"
X#include "in.h"
X#include "in_systm.h"
X#include "ip.h"
X#include "ip_var.h"
X
X/*
X * Raw interface to IP protocol.
X */
X
Xstruct	sockaddr_in ripdst = { AF_INET };
Xstruct	sockaddr_in ripsrc = { AF_INET };
Xstruct	sockproto ripproto = { PF_INET };
X/*
X * Setup generic address and protocol structures
X * for raw_input routine, then pass them along with
X * mbuf chain.
X */
Xrip_input(m)
X	struct mbuf *m;
X{
X	register struct ip *ip = mtod(m, struct ip *);
X
X	ripproto.sp_protocol = ip->ip_p;
X	ripdst.sin_addr = ip->ip_dst;
X	ripsrc.sin_addr = ip->ip_src;
X	raw_input(m, &ripproto, (struct sockaddr *)&ripsrc,
X	  (struct sockaddr *)&ripdst);
X}
X
Xrip_output(m, so)
X	register struct mbuf *m;
X	struct socket *so;
X{
X	register struct ip *ip;
X	int error;
X	struct rawcb *rp = sotorawcb(so);
X	struct sockaddr_in *sin;
X#if BSD>=43
X	short proto = rp->rcb_proto.sp_protocol;
X#else
X	short proto = so->so_proto->pr_protocol;
X#endif
X	/*
X	 * if the protocol is IPPROTO_RAW, the user handed us a 
X	 * complete IP packet.  Otherwise, allocate an mbuf for a
X	 * header and fill it in as needed.
X	 */
X	if (proto != IPPROTO_RAW) {
X		/*
X		 * Calculate data length and get an mbuf
X		 * for IP header.
X		 */
X		int len = 0;
X		struct mbuf *m0;
X
X		for (m0 = m; m; m = m->m_next)
X			len += m->m_len;
X
X		m = m_get(M_DONTWAIT, MT_HEADER);
X		if (m == 0) {
X			m = m0;
X			error = ENOBUFS;
X			goto bad;
X		}
X		m->m_off = MMAXOFF - sizeof(struct ip);
X		m->m_len = sizeof(struct ip);
X		m->m_next = m0;
X
X		ip = mtod(m, struct ip *);
X		ip->ip_tos = 0;
X		ip->ip_off = 0;
X		ip->ip_p = proto;
X		ip->ip_len = sizeof(struct ip) + len;
X		ip->ip_ttl = MAXTTL;
X	} else
X		ip = mtod(m, struct ip *);
X
X	if (rp->rcb_flags & RAW_LADDR) {
X		sin = (struct sockaddr_in *)&rp->rcb_laddr;
X		if (sin->sin_family != AF_INET) {
X			error = EAFNOSUPPORT;
X			goto bad;
X		}
X		ip->ip_src.s_addr = sin->sin_addr.s_addr;
X	} else
X		ip->ip_src.s_addr = 0;
X
X	ip->ip_dst = ((struct sockaddr_in *)&rp->rcb_faddr)->sin_addr;
X
X#if BSD>=43
X	return (ip_output(m, rp->rcb_options, &rp->rcb_route, 
X	   (so->so_options & SO_DONTROUTE) | IP_ALLOWBROADCAST));
X#else
X	return (ip_output(m, (struct mbuf *)0, &rp->rcb_route, 
X	   (so->so_options & SO_DONTROUTE) | IP_ALLOWBROADCAST));
X#endif
Xbad:
X	m_freem(m);
X	return (error);
X}
X
X/*
X * Raw IP socket option processing.
X */
Xrip_ctloutput(op, so, level, optname, m)
X	int op;
X	struct socket *so;
X	int level, optname;
X	struct mbuf **m;
X{
X	int error = 0;
X	register struct rawcb *rp = sotorawcb(so);
X
X	if (level != IPPROTO_IP)
X		error = EINVAL;
X	else switch (op) {
X
X	case PRCO_SETOPT:
X		switch (optname) {
X		case IP_OPTIONS:
X			return (ip_pcbopts(&rp->rcb_options, *m));
X
X		default:
X			error = EINVAL;
X			break;
X		}
X		break;
X
X	case PRCO_GETOPT:
X		switch (optname) {
X		case IP_OPTIONS:
X			*m = m_get(M_WAIT, MT_SOOPTS);
X			if (rp->rcb_options) {
X				(*m)->m_off = rp->rcb_options->m_off;
X				(*m)->m_len = rp->rcb_options->m_len;
X				bcopy(mtod(rp->rcb_options, caddr_t),
X				    mtod(*m, caddr_t), (unsigned)(*m)->m_len);
X			} else
X				(*m)->m_len = 0;
X			break;
X		default:
X			error = EINVAL;
X			break;
X		}
X		break;
X	}
X	if (op == PRCO_SETOPT && *m)
X		(void)m_free(*m);
X	return (error);
X}
SHAR_EOF
fi
if test -f 'Makefile'
then
	echo shar: "will not over-write existing file 'Makefile'"
else
sed 's/^X//' << \SHAR_EOF > 'Makefile'
XINCL =
XCFLAGS = -O
XLIBS =
X
Xtraceroute: traceroute.c
X	cc $(CFLAGS) $(INCL) -o traceroute traceroute.c $(LIBS)
X
Xinstall: traceroute
X	install -s -o root -g bin -m 4551 traceroute ${DESTDIR}/etc/traceroute 
X
Xlint:
X	lint -b -h -x $(INCL) traceroute.c | \
X	  grep -v 'possible pointer alignment problem'
SHAR_EOF
fi
if test -f 'traceroute.8'
then
	echo shar: "will not over-write existing file 'traceroute.8'"
else
sed 's/^X//' << \SHAR_EOF > 'traceroute.8'
X.\" Copyright (c) 1988 The Regents of the University of California.
X.\" All rights reserved.
X.\"
X.\" Redistribution and use in source and binary forms are permitted
X.\" provided that the above copyright notice and this paragraph are
X.\" duplicated in all such forms and that any documentation,
X.\" advertising materials, and other materials related to such
X.\" distribution and use acknowledge that the software was developed
X.\" by the University of California, Berkeley.  The name of the
X.\" University may not be used to endorse or promote products derived
X.\" from this software without specific prior written permission.
X.\" THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
X.\" IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
X.\" WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
X.\"
X.\"	$Header: traceroute.8,v 1.1 89/02/28 20:46:12 van Exp $
X.\"
X.TH TRACEROUTE 8 "February 28, 1989"
X.UC 6
X.SH NAME
Xtraceroute \- print the route packets take to network host
X.SH SYNOPSIS
X.B traceroute
X[
X.B \-m
Xmax_ttl
X] [
X.B \-n
X] [
X.B \-p
Xport
X] [
X.B \-q
Xnqueries
X] [
X.B \-r
X] [
X.B \-s
Xsrc_addr
X] [
X.B \-t
Xtos
X] [
X.B \-w
X] [
X.B \-w
Xwaittime
X]
X.I host
X[
X.I packetsize
X]
X.SH DESCRIPTION
XThe Internet is a large and complex aggregation of
Xnetwork hardware, connected together by gateways.
XTracking the route one's packets follow (or finding the miscreant
Xgateway that's discarding your packets) can be difficult.
X.I Traceroute
Xutilizes the IP protocol `time to live' field and attempts to elicit an
XICMP TIME_EXCEEDED response from each gateway along the path to some
Xhost.
X
XThe only mandatory parameter is the destination host name or IP number.
XThe default probe datagram length is 38 bytes, but this may be increased
Xby specifying a packet size (in bytes) after the destination host
Xname.
X
XOther options are:
X.TP
X.B \-m
XSet the max time-to-live (max number of hops) used in outgoing probe
Xpackets.  The default is 30 hops (the same default used for TCP
Xconnections).
X.TP
X.B \-n
XPrint hop addresses numerically rather than symbolically and numerically
X(saves a nameserver address-to-name lookup for each gateway found on the
Xpath).
X.TP
X.B \-p
XSet the base UDP port number used in probes (default is 33434).
XTraceroute hopes that nothing is listening on UDP ports
X.I base
Xto
X.I base+nhops-1
Xat the destination host (so an ICMP PORT_UNREACHABLE message will
Xbe returned to terminate the route tracing).  If something is
Xlistening on a port in the default range, this option can be used
Xto pick an unused port range.
X.TP
X.B \-r
XBypass the normal routing tables and send directly to a host on an attached
Xnetwork.
XIf the host is not on a directly-attached network,
Xan error is returned.
XThis option can be used to ping a local host through an interface
Xthat has no route through it (e.g., after the interface was dropped by
X.IR routed (8C)).
X.TP
X.B \-s
XUse the following IP address (which must be given as an IP number, not
Xa hostname) as the source address in outgoing probe packets.  On
Xhosts with more than one IP address, this option can be used to
Xforce the source address to be something other than the IP address
Xof the interface the probe packet is sent on.  If the IP address
Xis not one of this machine's interface addresses, an error is
Xreturned and nothing is sent.
X.TP
X.B \-t
XSet the
X.I type-of-service
Xin probe packets to the following value (default zero).  The value must be 
Xa decimal integer in the range 0 to 255.  This option can be used to
Xsee if different types-of-service result in different paths.  (If you
Xare not running 4.4bsd, this may be academic since the normal network
Xservices like telnet and ftp don't let you control the TOS).
XNot all values of TOS are legal or
Xmeaningful \- see the IP spec for definitions.  Useful values are
Xprobably `-t 16' (low delay) and `-t 8' (high throughput).
X.TP
X.B \-v
XVerbose output.  Received ICMP packets other than TIME_EXCEEDED and
XUNREACHABLEs are listed.
X.TP
X.B \-w
XSet the time (in seconds) to wait for a response to a probe (default 3
Xsec.).
X.PP
XThis program attempts to trace the route an IP packet would follow to some
Xinternet host by launching UDP probe
Xpackets with a small ttl (time to live) then listening for an
XICMP "time exceeded" reply from a gateway.  We start our probes
Xwith a ttl of one and increase by one until we get an ICMP "port
Xunreachable" (which means we got to "host") or hit a max (which
Xdefaults to 30 hops & can be changed with the \-m flag).  Three
Xprobes (change with \-q flag) are sent at each ttl setting and a
Xline is printed showing the ttl, address of the gateway and
Xround trip time of each probe.  If the probe answers come from
Xdifferent gateways, the address of each responding system will
Xbe printed.  If there is no response within a 3 sec. timeout
Xinterval (changed with the \-w flag), a "*" is printed for that
Xprobe.
X.PP
XWe don't want the destination
Xhost to process the UDP probe packets so the destination port is set to an
Xunlikely value (if some clod on the destination is using that
Xvalue, it can be changed with the \-p flag).
X.PP
XA sample use and output might be:
X
X.RS
X.nf
X[yak 71]% traceroute nis.nsf.net.
Xtraceroute to nis.nsf.net (35.1.1.48), 30 hops max, 56 byte packet
X 1  helios.ee.lbl.gov (128.3.112.1)  19 ms  19 ms  0 ms
X 2  lilac-dmc.Berkeley.EDU (128.32.216.1)  39 ms  39 ms  19 ms
X 3  lilac-dmc.Berkeley.EDU (128.32.216.1)  39 ms  39 ms  19 ms
X 4  ccngw-ner-cc.Berkeley.EDU (128.32.136.23)  39 ms  40 ms  39 ms
X 5  ccn-nerif22.Berkeley.EDU (128.32.168.22)  39 ms  39 ms  39 ms
X 6  128.32.197.4 (128.32.197.4)  40 ms  59 ms  59 ms
X 7  131.119.2.5 (131.119.2.5)  59 ms  59 ms  59 ms
X 8  129.140.70.13 (129.140.70.13)  99 ms  99 ms  80 ms
X 9  129.140.71.6 (129.140.71.6)  139 ms  239 ms  319 ms
X10  129.140.81.7 (129.140.81.7)  220 ms  199 ms  199 ms
X11  nic.merit.edu (35.1.1.48)  239 ms  239 ms  239 ms
X.fi
X.RE
X
XNote that lines 2 & 3 are the same.  This is due to a buggy
Xkernel on the 2nd hop system \- lbl-csam.arpa \- that forwards
Xpackets with a zero ttl (a bug in the distributed version
Xof 4.3BSD).  Note that you have to guess what path
Xthe packets are taking cross-country since the NSFNet (129.140)
Xdoesn't supply address-to-name translations for its NSSes.
X.PP
XA more interesting example is:
X
X.RS
X.nf
X[yak 72]% traceroute allspice.lcs.mit.edu.
Xtraceroute to allspice.lcs.mit.edu (18.26.0.115), 30 hops max
X 1  helios.ee.lbl.gov (128.3.112.1)  0 ms  0 ms  0 ms
X 2  lilac-dmc.Berkeley.EDU (128.32.216.1)  19 ms  19 ms  19 ms
X 3  lilac-dmc.Berkeley.EDU (128.32.216.1)  39 ms  19 ms  19 ms
X 4  ccngw-ner-cc.Berkeley.EDU (128.32.136.23)  19 ms  39 ms  39 ms
X 5  ccn-nerif22.Berkeley.EDU (128.32.168.22)  20 ms  39 ms  39 ms
X 6  128.32.197.4 (128.32.197.4)  59 ms  119 ms  39 ms
X 7  131.119.2.5 (131.119.2.5)  59 ms  59 ms  39 ms
X 8  129.140.70.13 (129.140.70.13)  80 ms  79 ms  99 ms
X 9  129.140.71.6 (129.140.71.6)  139 ms  139 ms  159 ms
X10  129.140.81.7 (129.140.81.7)  199 ms  180 ms  300 ms
X11  129.140.72.17 (129.140.72.17)  300 ms  239 ms  239 ms
X12  * * *
X13  128.121.54.72 (128.121.54.72)  259 ms  499 ms  279 ms
X14  * * *
X15  * * *
X16  * * *
X17  * * *
X18  ALLSPICE.LCS.MIT.EDU (18.26.0.115)  339 ms  279 ms  279 ms
X.fi
X.RE
X
XNote that the gateways 12, 14, 15, 16 & 17 hops away
Xeither don't send ICMP "time exceeded" messages or send them
Xwith a ttl too small to reach us.  14 \- 17 are running the
XMIT C Gateway code that doesn't send "time exceeded"s.  God
Xonly knows what's going on with 12.
X.PP
XThe silent gateway 12 in the above may be the result of a bug in
Xthe 4.[23]BSD network code (and its derivatives):  4.x (x <= 3)
Xsends an unreachable message using whatever ttl remains in the
Xoriginal datagram.  Since, for gateways, the remaining ttl is
Xzero, the ICMP "time exceeded" is guaranteed to not make it back
Xto us.  The behavior of this bug is slightly more interesting
Xwhen it appears on the destination system:
X
X.RS
X.nf
X 1  helios.ee.lbl.gov (128.3.112.1)  0 ms  0 ms  0 ms
X 2  lilac-dmc.Berkeley.EDU (128.32.216.1)  39 ms  19 ms  39 ms
X 3  lilac-dmc.Berkeley.EDU (128.32.216.1)  19 ms  39 ms  19 ms
X 4  ccngw-ner-cc.Berkeley.EDU (128.32.136.23)  39 ms  40 ms  19 ms
X 5  ccn-nerif35.Berkeley.EDU (128.32.168.35)  39 ms  39 ms  39 ms
X 6  csgw.Berkeley.EDU (128.32.133.254)  39 ms  59 ms  39 ms
X 7  * * *
X 8  * * *
X 9  * * *
X10  * * *
X11  * * *
X12  * * *
X13  rip.Berkeley.EDU (128.32.131.22)  59 ms !  39 ms !  39 ms !
X.fi
X.RE
X
XNotice that there are 12 "gateways" (13 is the final
Xdestination) and exactly the last half of them are "missing".
XWhat's really happening is that rip (a Sun-3 running Sun OS3.5)
Xis using the ttl from our arriving datagram as the ttl in its
XICMP reply.  So, the reply will time out on the return path
X(with no notice sent to anyone since ICMP's aren't sent for
XICMP's) until we probe with a ttl that's at least twice the path
Xlength.  I.e., rip is really only 7 hops away.  A reply that
Xreturns with a ttl of 1 is a clue this problem exists.
XTraceroute prints a "!" after the time if the ttl is <= 1.
XSince vendors ship a lot of obsolete (DEC's Ultrix, Sun 3.x) or
Xnon-standard (HPUX) software, expect to see this problem
Xfrequently and/or take care picking the target host of your
Xprobes.
X
XOther possible annotations after the time are
X.BR !H ,
X.BR !N ,
X.B !P
X(got a host, network or protocol unreachable, respectively),
X.B !S
Xor
X.B !F
X(source route failed or fragmentation needed \- neither of these should
Xever occur and the associated gateway is busted if you see one).  If
Xalmost all the probes result in some kind of unreachable, traceroute
Xwill give up and exit.
X.PP
XThis program is intended for use in network testing, measurement
Xand management.
XIt should be used primarily for manual fault isolation.
XBecause of the load it could impose on the network, it is unwise to use
X.I traceroute
Xduring normal operations or from automated scripts.
X.SH AUTHOR
XImplemented by Van Jacobson from a suggestion by Steve Deering.  Debugged
Xby a cast of thousands with particularly cogent suggestions or fixes from
XC. Philip Wood, Tim Seaver and Ken Adelman.
X.SH SEE ALSO
Xnetstat(1), ping(8)
SHAR_EOF
fi
if test -f 'traceroute.c'
then
	echo shar: "will not over-write existing file 'traceroute.c'"
else
sed 's/^X//' << \SHAR_EOF > 'traceroute.c'
X#ifndef lint
Xstatic char *rcsid =
X	"@(#)$Header: traceroute.c,v 1.17 89/02/28 21:01:13 van Exp $ (LBL)";
X#endif
X
X/*
X * traceroute host  - trace the route ip packets follow going to "host".
X *
X * Attempt to trace the route an ip packet would follow to some
X * internet host.  We find out intermediate hops by launching probe
X * packets with a small ttl (time to live) then listening for an
X * icmp "time exceeded" reply from a gateway.  We start our probes
X * with a ttl of one and increase by one until we get an icmp "port
X * unreachable" (which means we got to "host") or hit a max (which
X * defaults to 30 hops & can be changed with the -m flag).  Three
X * probes (change with -q flag) are sent at each ttl setting and a
X * line is printed showing the ttl, address of the gateway and
X * round trip time of each probe.  If the probe answers come from
X * different gateways, the address of each responding system will
X * be printed.  If there is no response within a 5 sec. timeout
X * interval (changed with the -w flag), a "*" is printed for that
X * probe.
X *
X * Probe packets are UDP format.  We don't want the destination
X * host to process them so the destination port is set to an
X * unlikely value (if some clod on the destination is using that
X * value, it can be changed with the -p flag).
X *
X * A sample use might be:
X *
X *     [yak 71]% traceroute nis.nsf.net.
X *     traceroute to nis.nsf.net (35.1.1.48), 30 hops max, 56 byte packet
X *      1  helios.ee.lbl.gov (128.3.112.1)  19 ms  19 ms  0 ms
X *      2  lilac-dmc.Berkeley.EDU (128.32.216.1)  39 ms  39 ms  19 ms
X *      3  lilac-dmc.Berkeley.EDU (128.32.216.1)  39 ms  39 ms  19 ms
X *      4  ccngw-ner-cc.Berkeley.EDU (128.32.136.23)  39 ms  40 ms  39 ms
X *      5  ccn-nerif22.Berkeley.EDU (128.32.168.22)  39 ms  39 ms  39 ms
X *      6  128.32.197.4 (128.32.197.4)  40 ms  59 ms  59 ms
X *      7  131.119.2.5 (131.119.2.5)  59 ms  59 ms  59 ms
X *      8  129.140.70.13 (129.140.70.13)  99 ms  99 ms  80 ms
X *      9  129.140.71.6 (129.140.71.6)  139 ms  239 ms  319 ms
X *     10  129.140.81.7 (129.140.81.7)  220 ms  199 ms  199 ms
X *     11  nic.merit.edu (35.1.1.48)  239 ms  239 ms  239 ms
X *
X * Note that lines 2 & 3 are the same.  This is due to a buggy
X * kernel on the 2nd hop system -- lbl-csam.arpa -- that forwards
X * packets with a zero ttl.
X *
X * A more interesting example is:
X *
X *     [yak 72]% traceroute allspice.lcs.mit.edu.
X *     traceroute to allspice.lcs.mit.edu (18.26.0.115), 30 hops max
X *      1  helios.ee.lbl.gov (128.3.112.1)  0 ms  0 ms  0 ms
X *      2  lilac-dmc.Berkeley.EDU (128.32.216.1)  19 ms  19 ms  19 ms
X *      3  lilac-dmc.Berkeley.EDU (128.32.216.1)  39 ms  19 ms  19 ms
X *      4  ccngw-ner-cc.Berkeley.EDU (128.32.136.23)  19 ms  39 ms  39 ms
X *      5  ccn-nerif22.Berkeley.EDU (128.32.168.22)  20 ms  39 ms  39 ms
X *      6  128.32.197.4 (128.32.197.4)  59 ms  119 ms  39 ms
X *      7  131.119.2.5 (131.119.2.5)  59 ms  59 ms  39 ms
X *      8  129.140.70.13 (129.140.70.13)  80 ms  79 ms  99 ms
X *      9  129.140.71.6 (129.140.71.6)  139 ms  139 ms  159 ms
X *     10  129.140.81.7 (129.140.81.7)  199 ms  180 ms  300 ms
X *     11  129.140.72.17 (129.140.72.17)  300 ms  239 ms  239 ms
X *     12  * * *
X *     13  128.121.54.72 (128.121.54.72)  259 ms  499 ms  279 ms
X *     14  * * *
X *     15  * * *
X *     16  * * *
X *     17  * * *
X *     18  ALLSPICE.LCS.MIT.EDU (18.26.0.115)  339 ms  279 ms  279 ms
X *
X * (I start to see why I'm having so much trouble with mail to
X * MIT.)  Note that the gateways 12, 14, 15, 16 & 17 hops away
X * either don't send ICMP "time exceeded" messages or send them
X * with a ttl too small to reach us.  14 - 17 are running the
X * MIT C Gateway code that doesn't send "time exceeded"s.  God
X * only knows what's going on with 12.
X *
X * The silent gateway 12 in the above may be the result of a bug in
X * the 4.[23]BSD network code (and its derivatives):  4.x (x <= 3)
X * sends an unreachable message using whatever ttl remains in the
X * original datagram.  Since, for gateways, the remaining ttl is
X * zero, the icmp "time exceeded" is guaranteed to not make it back
X * to us.  The behavior of this bug is slightly more interesting
X * when it appears on the destination system:
X *
X *      1  helios.ee.lbl.gov (128.3.112.1)  0 ms  0 ms  0 ms
X *      2  lilac-dmc.Berkeley.EDU (128.32.216.1)  39 ms  19 ms  39 ms
X *      3  lilac-dmc.Berkeley.EDU (128.32.216.1)  19 ms  39 ms  19 ms
X *      4  ccngw-ner-cc.Berkeley.EDU (128.32.136.23)  39 ms  40 ms  19 ms
X *      5  ccn-nerif35.Berkeley.EDU (128.32.168.35)  39 ms  39 ms  39 ms
X *      6  csgw.Berkeley.EDU (128.32.133.254)  39 ms  59 ms  39 ms
X *      7  * * *
X *      8  * * *
X *      9  * * *
X *     10  * * *
X *     11  * * *
X *     12  * * *
X *     13  rip.Berkeley.EDU (128.32.131.22)  59 ms !  39 ms !  39 ms !
X *
X * Notice that there are 12 "gateways" (13 is the final
X * destination) and exactly the last half of them are "missing".
X * What's really happening is that rip (a Sun-3 running Sun OS3.5)
X * is using the ttl from our arriving datagram as the ttl in its
X * icmp reply.  So, the reply will time out on the return path
X * (with no notice sent to anyone since icmp's aren't sent for
X * icmp's) until we probe with a ttl that's at least twice the path
X * length.  I.e., rip is really only 7 hops away.  A reply that
X * returns with a ttl of 1 is a clue this problem exists.
X * Traceroute prints a "!" after the time if the ttl is <= 1.
X * Since vendors ship a lot of obsolete (DEC's Ultrix, Sun 3.x) or
X * non-standard (HPUX) software, expect to see this problem
X * frequently and/or take care picking the target host of your
X * probes.
X *
X * Other possible annotations after the time are !H, !N, !P (got a host,
X * network or protocol unreachable, respectively), !S or !F (source
X * route failed or fragmentation needed -- neither of these should
X * ever occur and the associated gateway is busted if you see one).  If
X * almost all the probes result in some kind of unreachable, traceroute
X * will give up and exit.
X *
X * Notes
X * -----
X * This program must be run by root or be setuid.  (I suggest that
X * you *don't* make it setuid -- casual use could result in a lot
X * of unnecessary traffic on our poor, congested nets.)
X *
X * This program requires a kernel mod that does not appear in any
X * system available from Berkeley:  A raw ip socket using proto
X * IPPROTO_RAW must interpret the data sent as an ip datagram (as
X * opposed to data to be wrapped in a ip datagram).  See the README
X * file that came with the source to this program for a description
X * of the mods I made to /sys/netinet/raw_ip.c.  Your mileage may
X * vary.  But, again, ANY 4.x (x < 4) BSD KERNEL WILL HAVE TO BE
X * MODIFIED TO RUN THIS PROGRAM.
X *
X * The udp port usage may appear bizarre (well, ok, it is bizarre).
X * The problem is that an icmp message only contains 8 bytes of
X * data from the original datagram.  8 bytes is the size of a udp
X * header so, if we want to associate replies with the original
X * datagram, the necessary information must be encoded into the
X * udp header (the ip id could be used but there's no way to
X * interlock with the kernel's assignment of ip id's and, anyway,
X * it would have taken a lot more kernel hacking to allow this
X * code to set the ip id).  So, to allow two or more users to
X * use traceroute simultaneously, we use this task's pid as the
X * source port (the high bit is set to move the port number out
X * of the "likely" range).  To keep track of which probe is being
X * replied to (so times and/or hop counts don't get confused by a
X * reply that was delayed in transit), we increment the destination
X * port number before each probe.
X *
X * Don't use this as a coding example.  I was trying to find a
X * routing problem and this code sort-of popped out after 48 hours
X * without sleep.  I was amazed it ever compiled, much less ran.
X *
X * I stole the idea for this program from Steve Deering.  Since
X * the first release, I've learned that had I attended the right
X * IETF working group meetings, I also could have stolen it from Guy
X * Almes or Matt Mathis.  I don't know (or care) who came up with
X * the idea first.  I envy the originators' perspicacity and I'm
X * glad they didn't keep the idea a secret.
X *
X * Tim Seaver, Ken Adelman and C. Philip Wood provided bug fixes and/or
X * enhancements to the original distribution.
X *
X * I've hacked up a round-trip-route version of this that works by
X * sending a loose-source-routed udp datagram through the destination
X * back to yourself.  Unfortunately, SO many gateways botch source
X * routing, the thing is almost worthless.  Maybe one day...
X *
X *  -- Van Jacobson (van at helios.ee.lbl.gov)
X *     Tue Dec 20 03:50:13 PST 1988
X *
X * Copyright (c) 1988 Regents of the University of California.
X * All rights reserved.
X *
X * Redistribution and use in source and binary forms are permitted
X * provided that the above copyright notice and this paragraph are
X * duplicated in all such forms and that any documentation,
X * advertising materials, and other materials related to such
X * distribution and use acknowledge that the software was developed
X * by the University of California, Berkeley.  The name of the
X * University may not be used to endorse or promote products derived
X * from this software without specific prior written permission.
X * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
X * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
X * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
X */
X
X#include <stdio.h>
X#include <errno.h>
X#include <strings.h>
X#include <sys/time.h>
X
X#include <sys/param.h>
X#include <sys/socket.h>
X#include <sys/file.h>
X#include <sys/ioctl.h>
X
X#include <netinet/in_systm.h>
X#include <netinet/in.h>
X#include <netinet/ip.h>
X#include <netinet/ip_icmp.h>
X#include <netinet/udp.h>
X#include <netdb.h>
X
X#define	MAXPACKET	65535	/* max ip packet size */
X#ifndef MAXHOSTNAMELEN
X#define MAXHOSTNAMELEN	64
X#endif
X
X#ifndef FD_SET
X#define NFDBITS         (8*sizeof(fd_set))
X#define FD_SETSIZE      NFDBITS
X#define FD_SET(n, p)    ((p)->fds_bits[(n)/NFDBITS] |= (1 << ((n) % NFDBITS)))
X#define FD_CLR(n, p)    ((p)->fds_bits[(n)/NFDBITS] &= ~(1 << ((n) % NFDBITS)))
X#define FD_ISSET(n, p)  ((p)->fds_bits[(n)/NFDBITS] & (1 << ((n) % NFDBITS)))
X#define FD_ZERO(p)      bzero((char *)(p), sizeof(*(p)))
X#endif
X
X#define Fprintf (void)fprintf
X#define Sprintf (void)sprintf
X#define Printf (void)printf
Xextern	int errno;
Xextern  char *malloc();
Xextern  char *inet_ntoa();
Xextern  u_long inet_addr();
X
X/*
X * format of a (udp) probe packet.
X */
Xstruct opacket {
X	struct ip ip;
X	struct udphdr udp;
X	u_char seq;		/* sequence number of this packet */
X	u_char ttl;		/* ttl packet left with */
X	struct timeval tv;	/* time packet left */
X};
X
Xu_char	packet[512];		/* last inbound (icmp) packet */
Xstruct opacket	*outpacket;	/* last output (udp) packet */
Xchar *inetname();
X
Xint s;				/* receive (icmp) socket file descriptor */
Xint sndsock;			/* send (udp) socket file descriptor */
Xstruct timezone tz;		/* leftover */
X
Xstruct sockaddr whereto;	/* Who to try to reach */
Xint datalen;			/* How much data */
X
Xchar *source = 0;
Xchar *hostname;
Xchar hnamebuf[MAXHOSTNAMELEN];
X
Xint nprobes = 3;
Xint max_ttl = 30;
Xu_short ident;
Xu_short port = 32768+666;	/* start udp dest port # for probe packets */
X
Xint options;			/* socket options */
Xint verbose;
Xint waittime = 5;		/* time to wait for response (in seconds) */
Xint nflag;			/* print addresses numerically */
X
Xchar usage[] =
X "Usage: traceroute [-dnrv] [-w wait] [-m max_ttl] [-p port#] [-q nqueries] [-t tos] [-s src_addr] host [data size]\n";
X
X
Xmain(argc, argv)
X	char *argv[];
X{
X	struct sockaddr_in from;
X	char **av = argv;
X	struct sockaddr_in *to = (struct sockaddr_in *) &whereto;
X	int on = 1;
X	struct protoent *pe;
X	int ttl, probe, i;
X	int seq = 0;
X	int tos = 0;
X	struct hostent *hp;
X
X	argc--, av++;
X	while (argc && *av[0] == '-')  {
X		while (*++av[0])
X			switch (*av[0]) {
X			case 'd':
X				options |= SO_DEBUG;
X				break;
X			case 'm':
X				argc--, av++;
X				max_ttl = atoi(av[0]);
X				if (max_ttl <= 1) {
X					Fprintf(stderr, "max ttl must be >1\n");
X					exit(1);
X				}
X				goto nextarg;
X			case 'n':
X				nflag++;
X				break;
X			case 'p':
X				argc--, av++;
X				port = atoi(av[0]);
X				if (port < 1) {
X					Fprintf(stderr, "port must be >0\n");
X					exit(1);
X				}
X				goto nextarg;
X			case 'q':
X				argc--, av++;
X				nprobes = atoi(av[0]);
X				if (nprobes < 1) {
X					Fprintf(stderr, "nprobes must be >0\n");
X					exit(1);
X				}
X				goto nextarg;
X			case 'r':
X				options |= SO_DONTROUTE;
X				break;
X			case 's':
X				/*
X				 * set the ip source address of the outbound
X				 * probe (e.g., on a multi-homed host).
X				 */
X				argc--, av++;
X				source = av[0];
X				goto nextarg;
X			case 't':
X				argc--, av++;
X				tos = atoi(av[0]);
X				if (tos < 0 || tos > 255) {
X					Fprintf(stderr, "tos must be 0 to 255\n");
X					exit(1);
X				}
X				goto nextarg;
X			case 'v':
X				verbose++;
X				break;
X			case 'w':
X				argc--, av++;
X				waittime = atoi(av[0]);
X				if (waittime <= 1) {
X					Fprintf(stderr, "wait must be >1 sec\n");
X					exit(1);
X				}
X				goto nextarg;
X			}
X	nextarg:
X		argc--, av++;
X	}
X	if (argc < 1)  {
X		Printf(usage);
X		exit(1);
X	}
X	setlinebuf (stdout);
X
X	(void) bzero((char *)&whereto, sizeof(struct sockaddr));
X	to->sin_family = AF_INET;
X	to->sin_addr.s_addr = inet_addr(av[0]);
X	if (to->sin_addr.s_addr != -1) {
X		(void) strcpy(hnamebuf, av[0]);
X		hostname = hnamebuf;
X	} else {
X		hp = gethostbyname(av[0]);
X		if (hp) {
X			to->sin_family = hp->h_addrtype;
X			bcopy(hp->h_addr, (caddr_t)&to->sin_addr, hp->h_length);
X			hostname = hp->h_name;
X		} else {
X			Printf("%s: unknown host %s\n", argv[0], av[0]);
X			exit(1);
X		}
X	}
X
X	if (argc >= 2)
X		datalen = atoi(av[1]);
X	if (datalen < 0 || datalen >= MAXPACKET - sizeof(struct opacket)) {
X		Fprintf(stderr, "traceroute: packet size must be 0 <= s < %ld\n",
X			MAXPACKET - sizeof(struct opacket));
X		exit(1);
X	}
X	datalen += sizeof(struct opacket);
X	outpacket = (struct opacket *)malloc((unsigned)datalen);
X	if (! outpacket) {
X		perror("traceroute: malloc");
X		exit(1);
X	}
X	(void) bzero((char *)outpacket, datalen);
X	outpacket->ip.ip_dst = to->sin_addr;
X	outpacket->ip.ip_tos = tos;
X
X	ident = (getpid() & 0xffff) | 0x8000;
X
X	if ((pe = getprotobyname("icmp")) == NULL) {
X		Fprintf(stderr, "icmp: unknown protocol\n");
X		exit(10);
X	}
X	if ((s = socket(AF_INET, SOCK_RAW, pe->p_proto)) < 0) {
X		perror("traceroute: icmp socket");
X		exit(5);
X	}
X	if (options & SO_DEBUG)
X		(void) setsockopt(s, SOL_SOCKET, SO_DEBUG,
X				  (char *)&on, sizeof(on));
X	if (options & SO_DONTROUTE)
X		(void) setsockopt(s, SOL_SOCKET, SO_DONTROUTE,
X				  (char *)&on, sizeof(on));
X
X	if ((sndsock = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) < 0) {
X		perror("traceroute: raw socket");
X		exit(5);
X	}
X#ifdef SO_SNDBUF
X	if (setsockopt(sndsock, SOL_SOCKET, SO_SNDBUF, (char *)&datalen,
X		       sizeof(datalen)) < 0) {
X		perror("traceroute: SO_SNDBUF");
X		exit(6);
X	}
X#endif SO_SNDBUF
X#ifdef IP_HDRINCL
X	if (setsockopt(sndsock, IPPROTO_IP, IP_HDRINCL, (char *)&on,
X		       sizeof(on)) < 0) {
X		perror("traceroute: IP_HDRINCL");
X		exit(6);
X	}
X#endif IP_HDRINCL
X	if (options & SO_DEBUG)
X		(void) setsockopt(sndsock, SOL_SOCKET, SO_DEBUG,
X				  (char *)&on, sizeof(on));
X	if (options & SO_DONTROUTE)
X		(void) setsockopt(sndsock, SOL_SOCKET, SO_DONTROUTE,
X				  (char *)&on, sizeof(on));
X
X	if (source) {
X		(void) bzero((char *)&from, sizeof(struct sockaddr));
X		from.sin_family = AF_INET;
X		from.sin_addr.s_addr = inet_addr(source);
X		if (from.sin_addr.s_addr == -1) {
X			Printf("traceroute: unknown host %s\n", source);
X			exit(1);
X		}
X		outpacket->ip.ip_src = from.sin_addr;
X#ifndef IP_HDRINCL
X		if (bind(sndsock, (struct sockaddr *)&from, sizeof(from)) < 0) {
X			perror ("traceroute: bind:");
X			exit (1);
X		}
X#endif IP_HDRINCL
X	}
X
X	Fprintf(stderr, "traceroute to %s (%s)", hostname,
X		inet_ntoa(to->sin_addr));
X	if (source)
X		Fprintf(stderr, " from %s", source);
X	Fprintf(stderr, ", %d hops max, %d byte packets\n", max_ttl, datalen);
X	(void) fflush(stderr);
X
X	for (ttl = 1; ttl <= max_ttl; ++ttl) {
X		u_long lastaddr = 0;
X		int got_there = 0;
X		int unreachable = 0;
X
X		Printf("%2d ", ttl);
X		for (probe = 0; probe < nprobes; ++probe) {
X			int cc;
X			struct timeval tv;
X			struct ip *ip;
X
X			(void) gettimeofday(&tv, &tz);
X			send_probe(++seq, ttl);
X			while (cc = wait_for_reply(s, &from)) {
X				if ((i = packet_ok(packet, cc, &from, seq))) {
X					int dt = deltaT(&tv);
X					if (from.sin_addr.s_addr != lastaddr) {
X						print(packet, cc, &from);
X						lastaddr = from.sin_addr.s_addr;
X					}
X					Printf("  %d ms", dt);
X					switch(i - 1) {
X					case ICMP_UNREACH_PORT:
X#ifndef ARCHAIC
X						ip = (struct ip *)packet;
X						if (ip->ip_ttl <= 1)
X							Printf(" !");
X#endif ARCHAIC
X						++got_there;
X						break;
X					case ICMP_UNREACH_NET:
X						++unreachable;
X						Printf(" !N");
X						break;
X					case ICMP_UNREACH_HOST:
X						++unreachable;
X						Printf(" !H");
X						break;
X					case ICMP_UNREACH_PROTOCOL:
X						++got_there;
X						Printf(" !P");
X						break;
X					case ICMP_UNREACH_NEEDFRAG:
X						++unreachable;
X						Printf(" !F");
X						break;
X					case ICMP_UNREACH_SRCFAIL:
X						++unreachable;
X						Printf(" !S");
X						break;
X					}
X					break;
X				}
X			}
X			if (cc == 0)
X				Printf(" *");
X			(void) fflush(stdout);
X		}
X		putchar('\n');
X		if (got_there || unreachable >= nprobes-1)
X			exit(0);
X	}
X}
X
Xwait_for_reply(sock, from)
X	int sock;
X	struct sockaddr_in *from;
X{
X	fd_set fds;
X	struct timeval wait;
X	int cc = 0;
X	int fromlen = sizeof (*from);
X
X	FD_ZERO(&fds);
X	FD_SET(sock, &fds);
X	wait.tv_sec = waittime; wait.tv_usec = 0;
X
X	if (select(sock+1, &fds, (fd_set *)0, (fd_set *)0, &wait) > 0)
X		cc=recvfrom(s, (char *)packet, sizeof(packet), 0,
X			    (struct sockaddr *)from, &fromlen);
X
X	return(cc);
X}
X
X
Xsend_probe(seq, ttl)
X{
X	struct opacket *op = outpacket;
X	struct ip *ip = &op->ip;
X	struct udphdr *up = &op->udp;
X	int i;
X
X	ip->ip_off = 0;
X	ip->ip_p = IPPROTO_UDP;
X	ip->ip_len = datalen;
X	ip->ip_ttl = ttl;
X
X	up->uh_sport = htons(ident);
X	up->uh_dport = htons(port+seq);
X	up->uh_ulen = htons((u_short)(datalen - sizeof(struct ip)));
X	up->uh_sum = 0;
X
X	op->seq = seq;
X	op->ttl = ttl;
X	(void) gettimeofday(&op->tv, &tz);
X
X	i = sendto(sndsock, (char *)outpacket, datalen, 0, &whereto,
X		   sizeof(struct sockaddr));
X	if (i < 0 || i != datalen)  {
X		if (i<0)
X			perror("sendto");
X		Printf("traceroute: wrote %s %d chars, ret=%d\n", hostname,
X			datalen, i);
X		(void) fflush(stdout);
X	}
X}
X
X
XdeltaT(tp)
X	struct timeval *tp;
X{
X	struct timeval tv;
X
X	(void) gettimeofday(&tv, &tz);
X	tvsub(&tv, tp);
X	return (tv.tv_sec*1000 + (tv.tv_usec + 500)/1000);
X}
X
X
X/*
X * Convert an ICMP "type" field to a printable string.
X */
Xchar *
Xpr_type(t)
X	u_char t;
X{
X	static char *ttab[] = {
X	"Echo Reply",	"ICMP 1",	"ICMP 2",	"Dest Unreachable",
X	"Source Quench", "Redirect",	"ICMP 6",	"ICMP 7",
X	"Echo",		"ICMP 9",	"ICMP 10",	"Time Exceeded",
X	"Param Problem", "Timestamp",	"Timestamp Reply", "Info Request",
X	"Info Reply"
X	};
X
X	if(t > 16)
X		return("OUT-OF-RANGE");
X
X	return(ttab[t]);
X}
X
X
Xpacket_ok(buf, cc, from, seq)
X	u_char *buf;
X	int cc;
X	struct sockaddr_in *from;
X	int seq;
X{
X	register struct icmp *icp;
X	u_char type, code;
X	int hlen;
X#ifndef ARCHAIC
X	struct ip *ip;
X
X	ip = (struct ip *) buf;
X	hlen = ip->ip_hl << 2;
X	if (cc < hlen + ICMP_MINLEN) {
X		if (verbose)
X			Printf("packet too short (%d bytes) from %s\n", cc,
X				inet_ntoa(from->sin_addr));
X		return (0);
X	}
X	cc -= hlen;
X	icp = (struct icmp *)(buf + hlen);
X#else
X	icp = (struct icmp *)buf;
X#endif ARCHAIC
X	type = icp->icmp_type; code = icp->icmp_code;
X	if ((type == ICMP_TIMXCEED && code == ICMP_TIMXCEED_INTRANS) ||
X	    type == ICMP_UNREACH) {
X		struct ip *hip;
X		struct udphdr *up;
X
X		hip = &icp->icmp_ip;
X		hlen = hip->ip_hl << 2;
X		up = (struct udphdr *)((u_char *)hip + hlen);
X		if (hlen + 12 <= cc && hip->ip_p == IPPROTO_UDP &&
X		    up->uh_sport == htons(ident) &&
X		    up->uh_dport == htons(port+seq))
X			return (type == ICMP_TIMXCEED? -1 : code+1);
X	}
X#ifndef ARCHAIC
X	if (verbose) {
X		int i;
X		u_long *lp = (u_long *)&icp->icmp_ip;
X
X		Printf("\n%d bytes from %s to %s", cc,
X			inet_ntoa(from->sin_addr), inet_ntoa(ip->ip_dst));
X		Printf(": icmp type %d (%s) code %d\n", type, pr_type(type),
X		       icp->icmp_code);
X		for (i = 4; i < cc ; i += sizeof(long))
X			Printf("%2d: x%8.8lx\n", i, *lp++);
X	}
X#endif ARCHAIC
X	return(0);
X}
X
X
Xprint(buf, cc, from)
X	u_char *buf;
X	int cc;
X	struct sockaddr_in *from;
X{
X	struct ip *ip;
X	int hlen;
X
X	ip = (struct ip *) buf;
X	hlen = ip->ip_hl << 2;
X	cc -= hlen;
X
X	if (nflag)
X		Printf(" %s", inet_ntoa(from->sin_addr));
X	else
X		Printf(" %s (%s)", inetname(from->sin_addr),
X		       inet_ntoa(from->sin_addr));
X
X	if (verbose)
X		Printf (" %d bytes to %s", cc, inet_ntoa (ip->ip_dst));
X}
X
X
X#ifdef notyet
X/*
X * Checksum routine for Internet Protocol family headers (C Version)
X */
Xin_cksum(addr, len)
Xu_short *addr;
Xint len;
X{
X	register int nleft = len;
X	register u_short *w = addr;
X	register u_short answer;
X	register int sum = 0;
X
X	/*
X	 *  Our algorithm is simple, using a 32 bit accumulator (sum),
X	 *  we add sequential 16 bit words to it, and at the end, fold
X	 *  back all the carry bits from the top 16 bits into the lower
X	 *  16 bits.
X	 */
X	while (nleft > 1)  {
X		sum += *w++;
X		nleft -= 2;
X	}
X
X	/* mop up an odd byte, if necessary */
X	if (nleft == 1)
X		sum += *(u_char *)w;
X
X	/*
X	 * add back carry outs from top 16 bits to low 16 bits
X	 */
X	sum = (sum >> 16) + (sum & 0xffff);	/* add hi 16 to low 16 */
X	sum += (sum >> 16);			/* add carry */
X	answer = ~sum;				/* truncate to 16 bits */
X	return (answer);
X}
X#endif notyet
X
X/*
X * Subtract 2 timeval structs:  out = out - in.
X * Out is assumed to be >= in.
X */
Xtvsub(out, in)
Xregister struct timeval *out, *in;
X{
X	if ((out->tv_usec -= in->tv_usec) < 0)   {
X		out->tv_sec--;
X		out->tv_usec += 1000000;
X	}
X	out->tv_sec -= in->tv_sec;
X}
X
X
X/*
X * Construct an Internet address representation.
X * If the nflag has been supplied, give 
X * numeric value, otherwise try for symbolic name.
X */
Xchar *
Xinetname(in)
X	struct in_addr in;
X{
X	register char *cp;
X	static char line[50];
X	struct hostent *hp;
X	static char domain[MAXHOSTNAMELEN + 1];
X	static int first = 1;
X
X	if (first && !nflag) {
X		first = 0;
X		if (gethostname(domain, MAXHOSTNAMELEN) == 0 &&
X		    (cp = index(domain, '.')))
X			(void) strcpy(domain, cp + 1);
X		else
X			domain[0] = 0;
X	}
X	cp = 0;
X	if (!nflag && in.s_addr != INADDR_ANY) {
X		hp = gethostbyaddr((char *)&in, sizeof (in), AF_INET);
X		if (hp) {
X			if ((cp = index(hp->h_name, '.')) &&
X			    !strcmp(cp + 1, domain))
X				*cp = 0;
X			cp = hp->h_name;
X		}
X	}
X	if (cp)
X		(void) strcpy(line, cp);
X	else {
X		in.s_addr = ntohl(in.s_addr);
X#define C(x)	((x) & 0xff)
X		Sprintf(line, "%lu.%lu.%lu.%lu", C(in.s_addr >> 24),
X			C(in.s_addr >> 16), C(in.s_addr >> 8), C(in.s_addr));
X	}
X	return (line);
X}
SHAR_EOF
fi
if test -f 'mean.awk'
then
	echo shar: "will not over-write existing file 'mean.awk'"
else
sed 's/^X//' << \SHAR_EOF > 'mean.awk'
X/^ *[0-9]/	{
X	# print out the average time to each hop along a route.
X	tottime = 0; n = 0;
X	for (f = 5; f <= NF; ++f) {
X		if ($f == "ms") {
X			tottime += $(f - 1)
X			++n
X		}
X	}
X	if (n > 0)
X		print $1, tottime/n, median
X}
SHAR_EOF
fi
if test -f 'median.awk'
then
	echo shar: "will not over-write existing file 'median.awk'"
else
sed 's/^X//' << \SHAR_EOF > 'median.awk'
X/^ *[0-9]/	{
X	# print out the median time to each hop along a route.
X	tottime = 0; n = 0;
X	for (f = 5; f <= NF; ++f) {
X		if ($f == "ms") {
X			++n
X			time[n] = $(f - 1)
X		}
X	}
X	if (n > 0) {
X		# insertion sort the times to find the median
X		for (i = 2; i <= n; ++i) {
X			v = time[i]; j = i - 1;
X			while (time[j] > v) {
X				time[j+1] = time[j];
X				j = j - 1;
X				if (j < 0)
X					break;
X			}
X			time[j+1] = v;
X		}
X		if (n > 1 && (n % 2) == 0)
X			median = (time[n/2] + time[(n/2) + 1]) / 2
X		else
X			median = time[(n+1)/2]
X
X		print $1, median
X	}
X}
SHAR_EOF
fi
exit 0
#	End of shell archive



More information about the Comp.bugs.2bsd mailing list