ping.c revision 77119
187866Ssheldonh/*
287866Ssheldonh * Copyright (c) 1989, 1993
387866Ssheldonh *	The Regents of the University of California.  All rights reserved.
487866Ssheldonh *
587866Ssheldonh * This code is derived from software contributed to Berkeley by
687866Ssheldonh * Mike Muuss.
787866Ssheldonh *
887866Ssheldonh * Redistribution and use in source and binary forms, with or without
987866Ssheldonh * modification, are permitted provided that the following conditions
1087866Ssheldonh * are met:
1187866Ssheldonh * 1. Redistributions of source code must retain the above copyright
1287866Ssheldonh *    notice, this list of conditions and the following disclaimer.
1387866Ssheldonh * 2. Redistributions in binary form must reproduce the above copyright
1487866Ssheldonh *    notice, this list of conditions and the following disclaimer in the
1587866Ssheldonh *    documentation and/or other materials provided with the distribution.
1687866Ssheldonh * 3. All advertising materials mentioning features or use of this software
1787866Ssheldonh *    must display the following acknowledgement:
1887866Ssheldonh *	This product includes software developed by the University of
1987866Ssheldonh *	California, Berkeley and its contributors.
2087866Ssheldonh * 4. Neither the name of the University nor the names of its contributors
2187866Ssheldonh *    may be used to endorse or promote products derived from this software
2287866Ssheldonh *    without specific prior written permission.
2387866Ssheldonh *
2487866Ssheldonh * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
2587866Ssheldonh * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
2687866Ssheldonh * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
2787866Ssheldonh * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
2887866Ssheldonh * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2987866Ssheldonh * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
3087866Ssheldonh * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
3187866Ssheldonh * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32100490Sbp * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3387866Ssheldonh * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3487866Ssheldonh * SUCH DAMAGE.
35136699Sobrien */
36136699Sobrien
37136699Sobrien#ifndef lint
3887866Ssheldonhstatic const char copyright[] =
3987866Ssheldonh"@(#) Copyright (c) 1989, 1993\n\
4087866Ssheldonh	The Regents of the University of California.  All rights reserved.\n";
4187866Ssheldonh#endif /* not lint */
4287866Ssheldonh
43136699Sobrien#ifndef lint
4487866Ssheldonh#if 0
4587866Ssheldonhstatic char sccsid[] = "@(#)ping.c	8.1 (Berkeley) 6/5/93";
4687866Ssheldonh#endif
4787866Ssheldonhstatic const char rcsid[] =
4887866Ssheldonh  "$FreeBSD: head/sbin/ping/ping.c 77119 2001-05-24 09:17:52Z phk $";
49258125Sglebius#endif /* not lint */
50258125Sglebius
51258125Sglebius/*
5287866Ssheldonh *			P I N G . C
5387866Ssheldonh *
5487866Ssheldonh * Using the Internet Control Message Protocol (ICMP) "ECHO" facility,
5587866Ssheldonh * measure round-trip-delays and packet loss across network paths.
56258125Sglebius *
5787866Ssheldonh * Author -
58258125Sglebius *	Mike Muuss
5987866Ssheldonh *	U. S. Army Ballistic Research Laboratory
6087866Ssheldonh *	December, 1983
6187866Ssheldonh *
6287866Ssheldonh * Status -
6387866Ssheldonh *	Public Domain.  Distribution Unlimited.
6487866Ssheldonh * Bugs -
6587866Ssheldonh *	More statistics could always be gathered.
6687866Ssheldonh *	This program has to run SUID to ROOT to access the ICMP socket.
6787866Ssheldonh */
6887866Ssheldonh
6987866Ssheldonh#include <sys/param.h>		/* NB: we rely on this for <sys/types.h> */
7087866Ssheldonh
7187866Ssheldonh#include <ctype.h>
7287866Ssheldonh#include <err.h>
7387866Ssheldonh#include <errno.h>
7487866Ssheldonh#include <math.h>
7587866Ssheldonh#include <netdb.h>
7687866Ssheldonh#include <signal.h>
7787866Ssheldonh#include <stdio.h>
7887866Ssheldonh#include <stdlib.h>
79258125Sglebius#include <string.h>
8087866Ssheldonh#include <sysexits.h>
8187866Ssheldonh#include <termios.h>
8287866Ssheldonh#include <unistd.h>
83258125Sglebius
8487866Ssheldonh#include <sys/socket.h>
85258125Sglebius#include <sys/time.h>
8687866Ssheldonh#include <sys/uio.h>
87258125Sglebius
8887866Ssheldonh#include <netinet/in.h>
8987866Ssheldonh#include <netinet/in_systm.h>
9087866Ssheldonh#include <netinet/ip.h>
91258125Sglebius#include <netinet/ip_icmp.h>
9287866Ssheldonh#include <netinet/ip_var.h>
93258125Sglebius#include <arpa/inet.h>
9487866Ssheldonh
9587866Ssheldonh#ifdef IPSEC
9687866Ssheldonh#include <netinet6/ipsec.h>
9787866Ssheldonh#endif /*IPSEC*/
9887866Ssheldonh
99258125Sglebius#define	PHDR_LEN	sizeof(struct timeval)
100258125Sglebius#define	DEFDATALEN	(64 - PHDR_LEN)	/* default data length */
10188282Ssheldonh#define	FLOOD_BACKOFF	20000		/* usecs to back off if F_FLOOD mode */
10287866Ssheldonh					/* runs out of buffer space */
10387866Ssheldonh#define	MAXIPLEN	60
10487866Ssheldonh#define	MAXICMPLEN	76
10587866Ssheldonh#define	MAXPACKET	(65536 - 60 - 8)/* max packet size */
10687866Ssheldonh#define	MAXWAIT		10		/* max seconds to wait for response */
107258125Sglebius#define	MAXALARM	(60 * 60)	/* max seconds for alarm timeout */
10887866Ssheldonh#define	NROUTES		9		/* number of record route slots */
109136699Sobrien
11087866Ssheldonh#define	A(bit)		rcvd_tbl[(bit)>>3]	/* identify byte in array */
11187866Ssheldonh#define	B(bit)		(1 << ((bit) & 0x07))	/* identify bit in byte */
11287866Ssheldonh#define	SET(bit)	(A(bit) |= B(bit))
11387866Ssheldonh#define	CLR(bit)	(A(bit) &= (~B(bit)))
114258125Sglebius#define	TST(bit)	(A(bit) & B(bit))
115258125Sglebius
116100490Sbp/* various options */
117100490Sbpint options;
118100490Sbp#define	F_FLOOD		0x0001
119100490Sbp#define	F_INTERVAL	0x0002
12087866Ssheldonh#define	F_NUMERIC	0x0004
12187866Ssheldonh#define	F_PINGFILLED	0x0008
122258125Sglebius#define	F_QUIET		0x0010
123258125Sglebius#define	F_RROUTE	0x0020
124258125Sglebius#define	F_SO_DEBUG	0x0040
12587866Ssheldonh#define	F_SO_DONTROUTE	0x0080
12687866Ssheldonh#define	F_VERBOSE	0x0100
12787866Ssheldonh#define	F_QUIET2	0x0200
12887866Ssheldonh#define	F_NOLOOP	0x0400
12987866Ssheldonh#define	F_MTTL		0x0800
130258125Sglebius#define	F_MIF		0x1000
13187866Ssheldonh#define	F_AUDIBLE	0x2000
132136699Sobrien#ifdef IPSEC
13387866Ssheldonh#ifdef IPSEC_POLICY_IPSEC
13487866Ssheldonh#define F_POLICY	0x4000
13587866Ssheldonh#endif /*IPSEC_POLICY_IPSEC*/
13687866Ssheldonh#endif /*IPSEC*/
137258125Sglebius#define	F_TTL		0x8000
138258125Sglebius#define	F_MISSED	0x10000
139100490Sbp
140100490Sbp/*
141100490Sbp * MAX_DUP_CHK is the number of bits in received table, i.e. the maximum
142100490Sbp * number of received sequence numbers we can keep track of.  Change 128
14387866Ssheldonh * to 8192 for complete accuracy...
14487866Ssheldonh */
145258125Sglebius#define	MAX_DUP_CHK	(8 * 128)
146258125Sglebiusint mx_dup_ck = MAX_DUP_CHK;
147258125Sglebiuschar rcvd_tbl[MAX_DUP_CHK / 8];
14887866Ssheldonh
14987866Ssheldonhstruct sockaddr whereto;	/* who to ping */
15087866Ssheldonhint datalen = DEFDATALEN;
15187866Ssheldonhint s;				/* socket file descriptor */
15287866Ssheldonhu_char outpack[MAXPACKET];
153258125Sglebiuschar BSPACE = '\b';		/* characters written for flood */
15487866Ssheldonhchar BBELL = '\a';		/* characters written for MISSED and AUDIBLE */
15587866Ssheldonhchar DOT = '.';
156136699Sobrienchar *hostname;
15787866Ssheldonhchar *shostname;
15887866Ssheldonhint ident;			/* process id to identify our packets */
15987866Ssheldonhint uid;			/* cached uid for micro-optimization */
16087866Ssheldonh
16187866Ssheldonh/* counters */
16287866Ssheldonhlong npackets;			/* max packets to transmit */
16387866Ssheldonhlong nreceived;			/* # of packets we got back */
164258125Sglebiuslong nrepeats;			/* number of duplicates */
165258125Sglebiuslong ntransmitted;		/* sequence # for outbound packets = #sent */
166100490Sbpint interval = 1000;		/* interval between packets, ms */
167100490Sbp
168100490Sbp/* timing */
169100490Sbpint timing;			/* flag to do timing */
17087866Ssheldonhdouble tmin = 999999999.0;	/* minimum round trip time */
171258125Sglebiusdouble tmax = 0.0;		/* maximum round trip time */
172258125Sglebiusdouble tsum = 0.0;		/* sum of all times, for doing average */
173258125Sglebiusdouble tsumsq = 0.0;		/* sum of all times squared, for std. dev. */
17487866Ssheldonh
17587866Ssheldonhvolatile sig_atomic_t finish_up;  /* nonzero if we've been told to finish up */
17687866Ssheldonhint reset_kerninfo;
17787866Ssheldonhvolatile sig_atomic_t siginfo_p;
17887866Ssheldonh
179258125Sglebiusstatic void fill(char *, char *);
18087866Ssheldonhstatic u_short in_cksum(u_short *, int);
18187866Ssheldonhstatic void check_status(void);
182136699Sobrienstatic void finish(void) __dead2;
18387866Ssheldonhstatic void pinger(void);
18487866Ssheldonhstatic char *pr_addr(struct in_addr);
18587866Ssheldonhstatic void pr_icmph(struct icmp *);
18687866Ssheldonhstatic void pr_iph(struct ip *);
187258125Sglebiusstatic void pr_pack(char *, int, struct sockaddr_in *, struct timeval *);
18887866Ssheldonhstatic void pr_retip(struct ip *);
18987866Ssheldonhstatic void status(int);
19087866Ssheldonhstatic void stopit(int);
191258125Sglebiusstatic void tvsub(struct timeval *, struct timeval *);
192258125Sglebiusstatic void usage(void) __dead2;
193100490Sbp
194100490Sbpint
195100490Sbpmain(argc, argv)
196100490Sbp	int argc;
19787866Ssheldonh	char *const *argv;
198258125Sglebius{
199258125Sglebius	struct timeval last, intvl;
200258125Sglebius	struct hostent *hp;
20187866Ssheldonh	struct sockaddr_in *to, sin;
20287866Ssheldonh	struct termios ts;
20387866Ssheldonh	register int i;
20487866Ssheldonh	int ch, hold, packlen, preload, sockerrno, almost_done = 0, ttl;
20587866Ssheldonh	struct in_addr ifaddr;
20687866Ssheldonh	unsigned char mttl, loop;
20787866Ssheldonh	u_char *datap, *packet;
20887866Ssheldonh	char *source = NULL, *target, hnamebuf[MAXHOSTNAMELEN];
20987866Ssheldonh	char snamebuf[MAXHOSTNAMELEN];
21087866Ssheldonh	char *ep;
21187866Ssheldonh	u_long ultmp;
21287866Ssheldonh#ifdef IP_OPTIONS
21387866Ssheldonh	char rspace[3 + 4 * NROUTES + 1];	/* record route space */
21487866Ssheldonh#endif
21587866Ssheldonh	struct sigaction si_sa;
21687866Ssheldonh	struct iovec iov;
21787866Ssheldonh	struct msghdr msg;
21887866Ssheldonh	struct sockaddr_in from;
21987866Ssheldonh	char ctrl[CMSG_SPACE(sizeof(struct timeval))];
22087866Ssheldonh#ifdef IPSEC_POLICY_IPSEC
22187866Ssheldonh	char *policy_in = NULL;
22287866Ssheldonh	char *policy_out = NULL;
22387866Ssheldonh#endif
224	unsigned long alarmtimeout;
225
226	/*
227	 * Do the stuff that we need root priv's for *first*, and
228	 * then drop our setuid bit.  Save error reporting for
229	 * after arg parsing.
230	 */
231	s = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
232	sockerrno = errno;
233
234	setuid(getuid());
235	uid = getuid();
236
237	alarmtimeout = preload = 0;
238
239	datap = &outpack[8 + PHDR_LEN];
240	while ((ch = getopt(argc, argv,
241		"AI:LQRS:T:c:adfi:l:m:np:qrs:t:v"
242#ifdef IPSEC
243#ifdef IPSEC_POLICY_IPSEC
244		"P:"
245#endif /*IPSEC_POLICY_IPSEC*/
246#endif /*IPSEC*/
247		)) != -1)
248	{
249		switch(ch) {
250		case 'A':
251			options |= F_MISSED;
252			break;
253		case 'a':
254			options |= F_AUDIBLE;
255			break;
256		case 'c':
257			ultmp = strtoul(optarg, &ep, 0);
258			if (*ep || ep == optarg || ultmp > LONG_MAX || !ultmp)
259				errx(EX_USAGE,
260				    "invalid count of packets to transmit: `%s'",
261				    optarg);
262			npackets = ultmp;
263			break;
264		case 'd':
265			options |= F_SO_DEBUG;
266			break;
267		case 'f':
268			if (uid) {
269				errno = EPERM;
270				err(EX_NOPERM, "-f flag");
271			}
272			options |= F_FLOOD;
273			setbuf(stdout, (char *)NULL);
274			break;
275		case 'i':		/* wait between sending packets */
276			{
277			    double t = strtod(optarg, &ep) * 1000.0;
278
279			    if (*ep || ep == optarg || t > (double)INT_MAX) {
280				    errx(
281					    EX_USAGE,
282					     "invalid timing interval: `%s'",
283					     optarg
284				    );
285			    }
286			    options |= F_INTERVAL;
287			    interval = (int)t;
288			    if (uid && interval < 1000) {
289				    errno = EPERM;
290				    err(EX_NOPERM, "-i interval too short");
291			    }
292			}
293			break;
294		case 'I':		/* multicast interface */
295			if (inet_aton(optarg, &ifaddr) == 0)
296				errx(EX_USAGE,
297				     "invalid multicast interface: `%s'",
298				     optarg);
299			options |= F_MIF;
300			break;
301		case 'l':
302			ultmp = strtoul(optarg, &ep, 0);
303			if (*ep || ep == optarg || ultmp > INT_MAX)
304				errx(EX_USAGE,
305				     "invalid preload value: `%s'", optarg);
306			if (uid) {
307				errno = EPERM;
308				err(EX_NOPERM, "-l flag");
309			}
310			preload = ultmp;
311			break;
312		case 'L':
313			options |= F_NOLOOP;
314			loop = 0;
315			break;
316		case 'm':		/* TTL */
317			ultmp = strtoul(optarg, &ep, 0);
318			if (*ep || ep == optarg || ultmp > 255)
319				errx(EX_USAGE, "invalid TTL: `%s'",
320				     optarg);
321			ttl = ultmp;
322			options |= F_TTL;
323			break;
324		case 'n':
325			options |= F_NUMERIC;
326			break;
327		case 'p':		/* fill buffer with user pattern */
328			options |= F_PINGFILLED;
329			fill((char *)datap, optarg);
330				break;
331		case 'Q':
332			options |= F_QUIET2;
333			break;
334		case 'q':
335			options |= F_QUIET;
336			break;
337		case 'R':
338			options |= F_RROUTE;
339			break;
340		case 'r':
341			options |= F_SO_DONTROUTE;
342			break;
343		case 's':		/* size of packet to send */
344			if (uid) {
345				errno = EPERM;
346				err(EX_NOPERM, "-s flag");
347			}
348			ultmp = strtoul(optarg, &ep, 0);
349			if (ultmp > MAXPACKET)
350				errx(EX_USAGE, "packet size too large: %lu",
351				     ultmp);
352			if (*ep || ep == optarg || !ultmp)
353				errx(EX_USAGE, "invalid packet size: `%s'",
354				     optarg);
355			datalen = ultmp;
356			break;
357		case 'S':
358			source = optarg;
359			break;
360		case 't':
361			alarmtimeout = strtoul(optarg, &ep, 0);
362			if ((alarmtimeout < 1) || (alarmtimeout == ULONG_MAX))
363				errx(EX_USAGE, "invalid timeout: `%s'",
364				    optarg);
365			if (alarmtimeout > MAXALARM)
366				errx(EX_USAGE, "invalid timeout: `%s' > %d",
367				    optarg, MAXALARM);
368			alarm((int)alarmtimeout);
369			break;
370		case 'T':		/* multicast TTL */
371			ultmp = strtoul(optarg, &ep, 0);
372			if (*ep || ep == optarg || ultmp > 255)
373				errx(EX_USAGE, "invalid multicast TTL: `%s'",
374				     optarg);
375			mttl = ultmp;
376			options |= F_MTTL;
377			break;
378		case 'v':
379			options |= F_VERBOSE;
380			break;
381#ifdef IPSEC
382#ifdef IPSEC_POLICY_IPSEC
383		case 'P':
384			options |= F_POLICY;
385			if (!strncmp("in", optarg, 2))
386				policy_in = strdup(optarg);
387			else if (!strncmp("out", optarg, 3))
388				policy_out = strdup(optarg);
389			else
390				errx(1, "invalid security policy");
391			break;
392#endif /*IPSEC_POLICY_IPSEC*/
393#endif /*IPSEC*/
394		default:
395			usage();
396		}
397	}
398
399	if (argc - optind != 1)
400		usage();
401	target = argv[optind];
402
403	if (source) {
404		bzero((char *)&sin, sizeof(sin));
405		sin.sin_family = AF_INET;
406		if (inet_aton(source, &sin.sin_addr) != 0) {
407			shostname = source;
408		} else {
409			hp = gethostbyname2(source, AF_INET);
410			if (!hp)
411				errx(EX_NOHOST, "cannot resolve %s: %s",
412				     source, hstrerror(h_errno));
413
414			sin.sin_len = sizeof sin;
415			if (hp->h_length > sizeof(sin.sin_addr))
416				errx(1,"gethostbyname2: illegal address");
417			memcpy(&sin.sin_addr, hp->h_addr_list[0],
418				sizeof (sin.sin_addr));
419			(void)strncpy(snamebuf, hp->h_name,
420				sizeof(snamebuf) - 1);
421			snamebuf[sizeof(snamebuf) - 1] = '\0';
422			shostname = snamebuf;
423		}
424		if (bind(s, (struct sockaddr *)&sin, sizeof sin) == -1)
425			err(1, "bind");
426	}
427
428	bzero((char *)&whereto, sizeof(struct sockaddr));
429	to = (struct sockaddr_in *)&whereto;
430	to->sin_family = AF_INET;
431	if (inet_aton(target, &to->sin_addr) != 0) {
432		hostname = target;
433	} else {
434		hp = gethostbyname2(target, AF_INET);
435		if (!hp)
436			errx(EX_NOHOST, "cannot resolve %s: %s",
437			     target, hstrerror(h_errno));
438
439		to->sin_len = sizeof *to;
440		if (hp->h_length > sizeof(to->sin_addr))
441			errx(1,"gethostbyname2 returned an illegal address");
442		memcpy(&to->sin_addr, hp->h_addr_list[0], sizeof to->sin_addr);
443		(void)strncpy(hnamebuf, hp->h_name, sizeof(hnamebuf) - 1);
444		hnamebuf[sizeof(hnamebuf) - 1] = '\0';
445		hostname = hnamebuf;
446	}
447
448	if (options & F_FLOOD && options & F_INTERVAL)
449		errx(EX_USAGE, "-f and -i: incompatible options");
450
451	if (options & F_FLOOD && IN_MULTICAST(ntohl(to->sin_addr.s_addr)))
452		errx(EX_USAGE,
453		     "-f flag cannot be used with multicast destination");
454	if (options & (F_MIF | F_NOLOOP | F_MTTL)
455	    && !IN_MULTICAST(ntohl(to->sin_addr.s_addr)))
456		errx(EX_USAGE,
457		     "-I, -L, -T flags cannot be used with unicast destination");
458
459	if (datalen >= PHDR_LEN)	/* can we time transfer */
460		timing = 1;
461	packlen = datalen + MAXIPLEN + MAXICMPLEN;
462	if (!(packet = (u_char *)malloc((size_t)packlen)))
463		err(EX_UNAVAILABLE, "malloc");
464
465	if (!(options & F_PINGFILLED))
466		for (i = PHDR_LEN; i < datalen; ++i)
467			*datap++ = i;
468
469	ident = getpid() & 0xFFFF;
470
471	if (s < 0) {
472		errno = sockerrno;
473		err(EX_OSERR, "socket");
474	}
475	hold = 1;
476	if (options & F_SO_DEBUG)
477		(void)setsockopt(s, SOL_SOCKET, SO_DEBUG, (char *)&hold,
478		    sizeof(hold));
479	if (options & F_SO_DONTROUTE)
480		(void)setsockopt(s, SOL_SOCKET, SO_DONTROUTE, (char *)&hold,
481		    sizeof(hold));
482#ifdef IPSEC
483#ifdef IPSEC_POLICY_IPSEC
484	if (options & F_POLICY) {
485		char *buf;
486		if (policy_in != NULL) {
487			buf = ipsec_set_policy(policy_in, strlen(policy_in));
488			if (buf == NULL)
489				errx(EX_CONFIG, "%s", ipsec_strerror());
490			if (setsockopt(s, IPPROTO_IP, IP_IPSEC_POLICY,
491					buf, ipsec_get_policylen(buf)) < 0)
492				err(EX_CONFIG, "ipsec policy cannot be configured");
493			free(buf);
494		}
495
496		if (policy_out != NULL) {
497			buf = ipsec_set_policy(policy_out, strlen(policy_out));
498			if (buf == NULL)
499				errx(EX_CONFIG, "%s", ipsec_strerror());
500			if (setsockopt(s, IPPROTO_IP, IP_IPSEC_POLICY,
501					buf, ipsec_get_policylen(buf)) < 0)
502				err(EX_CONFIG, "ipsec policy cannot be configured");
503			free(buf);
504		}
505	}
506#endif /*IPSEC_POLICY_IPSEC*/
507#endif /*IPSEC*/
508
509	/* record route option */
510	if (options & F_RROUTE) {
511#ifdef IP_OPTIONS
512		bzero(rspace, sizeof(rspace));
513		rspace[IPOPT_OPTVAL] = IPOPT_RR;
514		rspace[IPOPT_OLEN] = sizeof(rspace) - 1;
515		rspace[IPOPT_OFFSET] = IPOPT_MINOFF;
516		rspace[sizeof(rspace) - 1] = IPOPT_EOL;
517		if (setsockopt(s, IPPROTO_IP, IP_OPTIONS, rspace,
518		    sizeof(rspace)) < 0)
519			err(EX_OSERR, "setsockopt IP_OPTIONS");
520#else
521		errx(EX_UNAVAILABLE,
522		  "record route not available in this implementation");
523#endif /* IP_OPTIONS */
524	}
525
526	if (options & F_TTL) {
527		if (setsockopt(s, IPPROTO_IP, IP_TTL, &ttl,
528		    sizeof(ttl)) < 0) {
529			err(EX_OSERR, "setsockopt IP_TTL");
530		}
531	}
532	if (options & F_NOLOOP) {
533		if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_LOOP, &loop,
534		    sizeof(loop)) < 0) {
535			err(EX_OSERR, "setsockopt IP_MULTICAST_LOOP");
536		}
537	}
538	if (options & F_MTTL) {
539		if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL, &mttl,
540		    sizeof(mttl)) < 0) {
541			err(EX_OSERR, "setsockopt IP_MULTICAST_TTL");
542		}
543	}
544	if (options & F_MIF) {
545		if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_IF, &ifaddr,
546		    sizeof(ifaddr)) < 0) {
547			err(EX_OSERR, "setsockopt IP_MULTICAST_IF");
548		}
549	}
550#ifdef SO_TIMESTAMP
551	{ int on = 1;
552	if (setsockopt(s, SOL_SOCKET, SO_TIMESTAMP, &on, sizeof(on)) < 0)
553		err(EX_OSERR, "setsockopt SO_TIMESTAMP");
554	}
555#endif
556
557	/*
558	 * When pinging the broadcast address, you can get a lot of answers.
559	 * Doing something so evil is useful if you are trying to stress the
560	 * ethernet, or just want to fill the arp cache to get some stuff for
561	 * /etc/ethers.  But beware: RFC 1122 allows hosts to ignore broadcast
562	 * or multicast pings if they wish.
563	 */
564	hold = 48 * 1024;
565	(void)setsockopt(s, SOL_SOCKET, SO_RCVBUF, (char *)&hold,
566	    sizeof(hold));
567
568	if (to->sin_family == AF_INET) {
569		(void)printf("PING %s (%s)", hostname,
570		    inet_ntoa(to->sin_addr));
571		if (source)
572			(void)printf(" from %s", shostname);
573		(void)printf(": %d data bytes\n", datalen);
574	} else
575		(void)printf("PING %s: %d data bytes\n", hostname, datalen);
576
577	/*
578	 * Use sigaction() instead of signal() to get unambiguous semantics,
579	 * in particular with SA_RESTART not set.
580	 */
581
582	sigemptyset(&si_sa.sa_mask);
583	si_sa.sa_flags = 0;
584
585	si_sa.sa_handler = stopit;
586	if (sigaction(SIGINT, &si_sa, 0) == -1) {
587		err(EX_OSERR, "sigaction SIGINT");
588	}
589
590	si_sa.sa_handler = status;
591	if (sigaction(SIGINFO, &si_sa, 0) == -1) {
592		err(EX_OSERR, "sigaction");
593	}
594
595        if (alarmtimeout > 0) {
596		si_sa.sa_handler = stopit;
597		if (sigaction(SIGALRM, &si_sa, 0) == -1)
598			err(EX_OSERR, "sigaction SIGALRM");
599        }
600
601	bzero(&msg, sizeof(msg));
602	msg.msg_name = (caddr_t)&from;
603	msg.msg_iov = &iov;
604	msg.msg_iovlen = 1;
605#ifdef SO_TIMESTAMP
606	msg.msg_control = (caddr_t)ctrl;
607#endif
608	iov.iov_base = packet;
609	iov.iov_len = packlen;
610
611	if (tcgetattr(STDOUT_FILENO, &ts) != -1) {
612		reset_kerninfo = !(ts.c_lflag & NOKERNINFO);
613		ts.c_lflag |= NOKERNINFO;
614		tcsetattr(STDOUT_FILENO, TCSANOW, &ts);
615	}
616
617	while (preload--)		/* fire off them quickies */
618		pinger();
619
620	if (options & F_FLOOD) {
621		intvl.tv_sec = 0;
622		intvl.tv_usec = 10000;
623	} else {
624		intvl.tv_sec = interval / 1000;
625		intvl.tv_usec = interval % 1000 * 1000;
626	}
627
628	pinger();			/* send the first ping */
629	(void)gettimeofday(&last, NULL);
630
631	while (!finish_up) {
632		register int cc;
633		int n;
634		struct timeval timeout, now;
635		fd_set rfds;
636
637		check_status();
638		FD_ZERO(&rfds);
639		FD_SET(s, &rfds);
640		(void)gettimeofday(&now, NULL);
641		timeout.tv_sec = last.tv_sec + intvl.tv_sec - now.tv_sec;
642		timeout.tv_usec = last.tv_usec + intvl.tv_usec - now.tv_usec;
643		while (timeout.tv_usec < 0) {
644			timeout.tv_usec += 1000000;
645			timeout.tv_sec--;
646		}
647		while (timeout.tv_usec >= 1000000) {
648			timeout.tv_usec -= 1000000;
649			timeout.tv_sec++;
650		}
651		if (timeout.tv_sec < 0)
652			timeout.tv_sec = timeout.tv_usec = 0;
653		n = select(s + 1, &rfds, NULL, NULL, &timeout);
654		if (n < 0)
655			continue;	/* Must be EINTR. */
656		if (n == 1) {
657			struct timeval *t = 0;
658#ifdef SO_TIMESTAMP
659			struct cmsghdr *cmsg = (struct cmsghdr *)&ctrl;
660
661			msg.msg_controllen = sizeof(ctrl);
662#endif
663			msg.msg_namelen = sizeof(from);
664			if ((cc = recvmsg(s, &msg, 0)) < 0) {
665				if (errno == EINTR)
666					continue;
667				warn("recvmsg");
668				continue;
669			}
670#ifdef SO_TIMESTAMP
671			if (cmsg->cmsg_level == SOL_SOCKET &&
672			    cmsg->cmsg_type == SCM_TIMESTAMP &&
673			    cmsg->cmsg_len == CMSG_LEN(sizeof *t)) {
674				/* Copy to avoid alignment problems: */
675				memcpy(&now,CMSG_DATA(cmsg),sizeof(now));
676				t = &now;
677			}
678#endif
679			if (t == 0) {
680				(void)gettimeofday(&now, NULL);
681				t = &now;
682			}
683			pr_pack((char *)packet, cc, &from, t);
684			if (npackets && nreceived >= npackets)
685				break;
686		}
687		if (n == 0 || options & F_FLOOD) {
688			if (!npackets || ntransmitted < npackets)
689				pinger();
690			else {
691				if (almost_done)
692					break;
693				almost_done = 1;
694				intvl.tv_usec = 0;
695				if (nreceived) {
696					intvl.tv_sec = 2 * tmax / 1000;
697					if (!intvl.tv_sec)
698						intvl.tv_sec = 1;
699				} else
700					intvl.tv_sec = MAXWAIT;
701			}
702			(void)gettimeofday(&last, NULL);
703
704			if (ntransmitted != nreceived+1 && options & F_MISSED)
705				(void)write(STDOUT_FILENO, &BBELL, 1);
706		}
707	}
708	finish();
709	/* NOTREACHED */
710	exit(0);	/* Make the compiler happy */
711}
712
713/*
714 * stopit --
715 *	Set the global bit that causes the main loop to quit.
716 * Do NOT call finish() from here, since finish() does far too much
717 * to be called from a signal handler.
718 */
719void
720stopit(sig)
721	int sig;
722{
723	finish_up = 1;
724}
725
726/*
727 * pinger --
728 *	Compose and transmit an ICMP ECHO REQUEST packet.  The IP packet
729 * will be added on by the kernel.  The ID field is our UNIX process ID,
730 * and the sequence number is an ascending integer.  The first 8 bytes
731 * of the data portion are used to hold a UNIX "timeval" struct in host
732 * byte-order, to compute the round-trip time.
733 */
734static void
735pinger(void)
736{
737	register struct icmp *icp;
738	register int cc;
739	int i;
740
741	icp = (struct icmp *)outpack;
742	icp->icmp_type = ICMP_ECHO;
743	icp->icmp_code = 0;
744	icp->icmp_cksum = 0;
745	icp->icmp_seq = ntransmitted;
746	icp->icmp_id = ident;			/* ID */
747
748	CLR(icp->icmp_seq % mx_dup_ck);
749
750	if (timing)
751		(void)gettimeofday((struct timeval *)&outpack[8],
752		    (struct timezone *)NULL);
753
754	cc = datalen + PHDR_LEN;		/* skips ICMP portion */
755
756	/* compute ICMP checksum here */
757	icp->icmp_cksum = in_cksum((u_short *)icp, cc);
758
759	i = sendto(s, (char *)outpack, cc, 0, &whereto,
760	    sizeof(struct sockaddr));
761
762	if (i < 0 || i != cc)  {
763		if (i < 0) {
764			if (options & F_FLOOD && errno == ENOBUFS) {
765				usleep(FLOOD_BACKOFF);
766				return;
767			}
768			warn("sendto");
769		} else {
770			warn("%s: partial write: %d of %d bytes",
771			     hostname, i, cc);
772		}
773	}
774	ntransmitted++;
775	if (!(options & F_QUIET) && options & F_FLOOD)
776		(void)write(STDOUT_FILENO, &DOT, 1);
777}
778
779/*
780 * pr_pack --
781 *	Print out the packet, if it came from us.  This logic is necessary
782 * because ALL readers of the ICMP socket get a copy of ALL ICMP packets
783 * which arrive ('tis only fair).  This permits multiple copies of this
784 * program to be run without having intermingled output (or statistics!).
785 */
786static void
787pr_pack(buf, cc, from, tv)
788	char *buf;
789	int cc;
790	struct sockaddr_in *from;
791	struct timeval *tv;
792{
793	register struct icmp *icp;
794	register u_long l;
795	register int i, j;
796	register u_char *cp,*dp;
797	static int old_rrlen;
798	static char old_rr[MAX_IPOPTLEN];
799	struct ip *ip;
800	struct timeval *tp;
801	double triptime;
802	int hlen, dupflag;
803
804	/* Check the IP header */
805	ip = (struct ip *)buf;
806	hlen = ip->ip_hl << 2;
807	if (cc < hlen + ICMP_MINLEN) {
808		if (options & F_VERBOSE)
809			warn("packet too short (%d bytes) from %s", cc,
810			     inet_ntoa(from->sin_addr));
811		return;
812	}
813
814	/* Now the ICMP part */
815	cc -= hlen;
816	icp = (struct icmp *)(buf + hlen);
817	if (icp->icmp_type == ICMP_ECHOREPLY) {
818		if (icp->icmp_id != ident)
819			return;			/* 'Twas not our ECHO */
820		++nreceived;
821		triptime = 0.0;
822		if (timing) {
823			struct timeval tv1;
824#ifndef icmp_data
825			tp = (struct timeval *)&icp->icmp_ip;
826#else
827			tp = (struct timeval *)icp->icmp_data;
828#endif
829			/* Avoid unaligned data: */
830			memcpy(&tv1,tp,sizeof(tv1));
831			tvsub(tv, &tv1);
832 			triptime = ((double)tv->tv_sec) * 1000.0 +
833 			    ((double)tv->tv_usec) / 1000.0;
834			tsum += triptime;
835			tsumsq += triptime * triptime;
836			if (triptime < tmin)
837				tmin = triptime;
838			if (triptime > tmax)
839				tmax = triptime;
840		}
841
842		if (TST(icp->icmp_seq % mx_dup_ck)) {
843			++nrepeats;
844			--nreceived;
845			dupflag = 1;
846		} else {
847			SET(icp->icmp_seq % mx_dup_ck);
848			dupflag = 0;
849		}
850
851		if (options & F_QUIET)
852			return;
853
854		if (options & F_FLOOD)
855			(void)write(STDOUT_FILENO, &BSPACE, 1);
856		else {
857			(void)printf("%d bytes from %s: icmp_seq=%u", cc,
858			   inet_ntoa(*(struct in_addr *)&from->sin_addr.s_addr),
859			   icp->icmp_seq);
860			(void)printf(" ttl=%d", ip->ip_ttl);
861			if (timing)
862				(void)printf(" time=%.3f ms", triptime);
863			if (dupflag)
864				(void)printf(" (DUP!)");
865			if (options & F_AUDIBLE)
866				(void)write(STDOUT_FILENO, &BBELL, 1);
867			/* check the data */
868			cp = (u_char*)&icp->icmp_data[PHDR_LEN];
869			dp = &outpack[8 + PHDR_LEN];
870			for (i = PHDR_LEN; i < datalen; ++i, ++cp, ++dp) {
871				if (*cp != *dp) {
872	(void)printf("\nwrong data byte #%d should be 0x%x but was 0x%x",
873	    i, *dp, *cp);
874					printf("\ncp:");
875					cp = (u_char*)&icp->icmp_data[0];
876					for (i = 0; i < datalen; ++i, ++cp) {
877						if ((i % 32) == 8)
878							(void)printf("\n\t");
879						(void)printf("%x ", *cp);
880					}
881					printf("\ndp:");
882					cp = &outpack[8];
883					for (i = 0; i < datalen; ++i, ++cp) {
884						if ((i % 32) == 8)
885							(void)printf("\n\t");
886						(void)printf("%x ", *cp);
887					}
888					break;
889				}
890			}
891		}
892	} else {
893		/*
894		 * We've got something other than an ECHOREPLY.
895		 * See if it's a reply to something that we sent.
896		 * We can compare IP destination, protocol,
897		 * and ICMP type and ID.
898		 *
899		 * Only print all the error messages if we are running
900		 * as root to avoid leaking information not normally
901		 * available to those not running as root.
902		 */
903#ifndef icmp_data
904		struct ip *oip = &icp->icmp_ip;
905#else
906		struct ip *oip = (struct ip *)icp->icmp_data;
907#endif
908		struct icmp *oicmp = (struct icmp *)(oip + 1);
909
910		if (((options & F_VERBOSE) && uid == 0) ||
911		    (!(options & F_QUIET2) &&
912		     (oip->ip_dst.s_addr ==
913			 ((struct sockaddr_in *)&whereto)->sin_addr.s_addr) &&
914		     (oip->ip_p == IPPROTO_ICMP) &&
915		     (oicmp->icmp_type == ICMP_ECHO) &&
916		     (oicmp->icmp_id == ident))) {
917		    (void)printf("%d bytes from %s: ", cc,
918			pr_addr(from->sin_addr));
919		    pr_icmph(icp);
920		} else
921		    return;
922	}
923
924	/* Display any IP options */
925	cp = (u_char *)buf + sizeof(struct ip);
926
927	for (; hlen > (int)sizeof(struct ip); --hlen, ++cp)
928		switch (*cp) {
929		case IPOPT_EOL:
930			hlen = 0;
931			break;
932		case IPOPT_LSRR:
933			(void)printf("\nLSRR: ");
934			hlen -= 2;
935			j = *++cp;
936			++cp;
937			if (j > IPOPT_MINOFF)
938				for (;;) {
939					l = *++cp;
940					l = (l<<8) + *++cp;
941					l = (l<<8) + *++cp;
942					l = (l<<8) + *++cp;
943					if (l == 0) {
944						printf("\t0.0.0.0");
945					} else {
946						struct in_addr ina;
947						ina.s_addr = ntohl(l);
948						printf("\t%s", pr_addr(ina));
949					}
950				hlen -= 4;
951				j -= 4;
952				if (j <= IPOPT_MINOFF)
953					break;
954				(void)putchar('\n');
955			}
956			break;
957		case IPOPT_RR:
958			j = *++cp;		/* get length */
959			i = *++cp;		/* and pointer */
960			hlen -= 2;
961			if (i > j)
962				i = j;
963			i -= IPOPT_MINOFF;
964			if (i <= 0)
965				continue;
966			if (i == old_rrlen
967			    && cp == (u_char *)buf + sizeof(struct ip) + 2
968			    && !bcmp((char *)cp, old_rr, i)
969			    && !(options & F_FLOOD)) {
970				(void)printf("\t(same route)");
971				i = ((i + 3) / 4) * 4;
972				hlen -= i;
973				cp += i;
974				break;
975			}
976			if (i < MAX_IPOPTLEN) {
977				old_rrlen = i;
978				bcopy((char *)cp, old_rr, i);
979			} else
980				old_rrlen = 0;
981
982			(void)printf("\nRR: ");
983			j = 0;
984			for (;;) {
985				l = *++cp;
986				l = (l<<8) + *++cp;
987				l = (l<<8) + *++cp;
988				l = (l<<8) + *++cp;
989				if (l == 0) {
990					printf("\t0.0.0.0");
991				} else {
992					struct in_addr ina;
993					ina.s_addr = ntohl(l);
994					printf("\t%s", pr_addr(ina));
995				}
996				hlen -= 4;
997				i -= 4;
998				j += 4;
999				if (i <= 0)
1000					break;
1001				if (j >= MAX_IPOPTLEN) {
1002					(void) printf("\t(truncated route)");
1003					break;
1004				}
1005				(void)putchar('\n');
1006			}
1007			break;
1008		case IPOPT_NOP:
1009			(void)printf("\nNOP");
1010			break;
1011		default:
1012			(void)printf("\nunknown option %x", *cp);
1013			break;
1014		}
1015	if (!(options & F_FLOOD)) {
1016		(void)putchar('\n');
1017		(void)fflush(stdout);
1018	}
1019}
1020
1021/*
1022 * in_cksum --
1023 *	Checksum routine for Internet Protocol family headers (C Version)
1024 */
1025u_short
1026in_cksum(addr, len)
1027	u_short *addr;
1028	int len;
1029{
1030	register int nleft = len;
1031	register u_short *w = addr;
1032	register int sum = 0;
1033	union {
1034		u_short	us;
1035		u_char	uc[2];
1036	} last;
1037	u_short answer;
1038
1039	/*
1040	 * Our algorithm is simple, using a 32 bit accumulator (sum), we add
1041	 * sequential 16 bit words to it, and at the end, fold back all the
1042	 * carry bits from the top 16 bits into the lower 16 bits.
1043	 */
1044	while (nleft > 1)  {
1045		sum += *w++;
1046		nleft -= 2;
1047	}
1048
1049	/* mop up an odd byte, if necessary */
1050	if (nleft == 1) {
1051		last.uc[0] = *(u_char *)w;
1052		last.uc[1] = 0;
1053		sum += last.us;
1054	}
1055
1056	/* add back carry outs from top 16 bits to low 16 bits */
1057	sum = (sum >> 16) + (sum & 0xffff);	/* add hi 16 to low 16 */
1058	sum += (sum >> 16);			/* add carry */
1059	answer = ~sum;				/* truncate to 16 bits */
1060	return(answer);
1061}
1062
1063/*
1064 * tvsub --
1065 *	Subtract 2 timeval structs:  out = out - in.  Out is assumed to
1066 * be >= in.
1067 */
1068static void
1069tvsub(out, in)
1070	register struct timeval *out, *in;
1071{
1072	if ((out->tv_usec -= in->tv_usec) < 0) {
1073		--out->tv_sec;
1074		out->tv_usec += 1000000;
1075	}
1076	out->tv_sec -= in->tv_sec;
1077}
1078
1079/*
1080 * status --
1081 *	Print out statistics when SIGINFO is received.
1082 */
1083
1084static void
1085status(sig)
1086	int sig;
1087{
1088	siginfo_p = 1;
1089}
1090
1091static void
1092check_status()
1093{
1094	if (siginfo_p) {
1095		siginfo_p = 0;
1096		(void)fprintf(stderr,
1097	"\r%ld/%ld packets received (%.0f%%) %.3f min / %.3f avg / %.3f max\n",
1098		    nreceived, ntransmitted,
1099		    ntransmitted ? nreceived * 100.0 / ntransmitted : 0.0,
1100		    nreceived ? tmin : 0.0,
1101		    nreceived + nrepeats ? tsum / (nreceived + nrepeats) : tsum,
1102		    tmax);
1103	}
1104}
1105
1106/*
1107 * finish --
1108 *	Print out statistics, and give up.
1109 */
1110static void
1111finish()
1112{
1113	struct termios ts;
1114
1115	(void)signal(SIGINT, SIG_IGN);
1116	(void)signal(SIGALRM, SIG_IGN);
1117	(void)putchar('\n');
1118	(void)fflush(stdout);
1119	(void)printf("--- %s ping statistics ---\n", hostname);
1120	(void)printf("%ld packets transmitted, ", ntransmitted);
1121	(void)printf("%ld packets received, ", nreceived);
1122	if (nrepeats)
1123		(void)printf("+%ld duplicates, ", nrepeats);
1124	if (ntransmitted) {
1125		if (nreceived > ntransmitted)
1126			(void)printf("-- somebody's printing up packets!");
1127		else
1128			(void)printf("%d%% packet loss",
1129			    (int) (((ntransmitted - nreceived) * 100) /
1130			    ntransmitted));
1131	}
1132	(void)putchar('\n');
1133	if (nreceived && timing) {
1134		double n = nreceived + nrepeats;
1135		double avg = tsum / n;
1136		double vari = tsumsq / n - avg * avg;
1137		printf("round-trip min/avg/max/stddev = "
1138		       "%.3f/%.3f/%.3f/%.3f ms\n",
1139		    tmin, avg, tmax, sqrt(vari));
1140	}
1141	if (reset_kerninfo && tcgetattr(STDOUT_FILENO, &ts) != -1) {
1142		ts.c_lflag &= ~NOKERNINFO;
1143		tcsetattr(STDOUT_FILENO, TCSANOW, &ts);
1144	}
1145
1146	if (nreceived)
1147		exit(0);
1148	else
1149		exit(2);
1150}
1151
1152#ifdef notdef
1153static char *ttab[] = {
1154	"Echo Reply",		/* ip + seq + udata */
1155	"Dest Unreachable",	/* net, host, proto, port, frag, sr + IP */
1156	"Source Quench",	/* IP */
1157	"Redirect",		/* redirect type, gateway, + IP  */
1158	"Echo",
1159	"Time Exceeded",	/* transit, frag reassem + IP */
1160	"Parameter Problem",	/* pointer + IP */
1161	"Timestamp",		/* id + seq + three timestamps */
1162	"Timestamp Reply",	/* " */
1163	"Info Request",		/* id + sq */
1164	"Info Reply"		/* " */
1165};
1166#endif
1167
1168/*
1169 * pr_icmph --
1170 *	Print a descriptive string about an ICMP header.
1171 */
1172static void
1173pr_icmph(icp)
1174	struct icmp *icp;
1175{
1176	switch(icp->icmp_type) {
1177	case ICMP_ECHOREPLY:
1178		(void)printf("Echo Reply\n");
1179		/* XXX ID + Seq + Data */
1180		break;
1181	case ICMP_UNREACH:
1182		switch(icp->icmp_code) {
1183		case ICMP_UNREACH_NET:
1184			(void)printf("Destination Net Unreachable\n");
1185			break;
1186		case ICMP_UNREACH_HOST:
1187			(void)printf("Destination Host Unreachable\n");
1188			break;
1189		case ICMP_UNREACH_PROTOCOL:
1190			(void)printf("Destination Protocol Unreachable\n");
1191			break;
1192		case ICMP_UNREACH_PORT:
1193			(void)printf("Destination Port Unreachable\n");
1194			break;
1195		case ICMP_UNREACH_NEEDFRAG:
1196			(void)printf("frag needed and DF set (MTU %d)\n",
1197					ntohs(icp->icmp_nextmtu));
1198			break;
1199		case ICMP_UNREACH_SRCFAIL:
1200			(void)printf("Source Route Failed\n");
1201			break;
1202		case ICMP_UNREACH_FILTER_PROHIB:
1203			(void)printf("Communication prohibited by filter\n");
1204			break;
1205		default:
1206			(void)printf("Dest Unreachable, Bad Code: %d\n",
1207			    icp->icmp_code);
1208			break;
1209		}
1210		/* Print returned IP header information */
1211#ifndef icmp_data
1212		pr_retip(&icp->icmp_ip);
1213#else
1214		pr_retip((struct ip *)icp->icmp_data);
1215#endif
1216		break;
1217	case ICMP_SOURCEQUENCH:
1218		(void)printf("Source Quench\n");
1219#ifndef icmp_data
1220		pr_retip(&icp->icmp_ip);
1221#else
1222		pr_retip((struct ip *)icp->icmp_data);
1223#endif
1224		break;
1225	case ICMP_REDIRECT:
1226		switch(icp->icmp_code) {
1227		case ICMP_REDIRECT_NET:
1228			(void)printf("Redirect Network");
1229			break;
1230		case ICMP_REDIRECT_HOST:
1231			(void)printf("Redirect Host");
1232			break;
1233		case ICMP_REDIRECT_TOSNET:
1234			(void)printf("Redirect Type of Service and Network");
1235			break;
1236		case ICMP_REDIRECT_TOSHOST:
1237			(void)printf("Redirect Type of Service and Host");
1238			break;
1239		default:
1240			(void)printf("Redirect, Bad Code: %d", icp->icmp_code);
1241			break;
1242		}
1243		(void)printf("(New addr: %s)\n", inet_ntoa(icp->icmp_gwaddr));
1244#ifndef icmp_data
1245		pr_retip(&icp->icmp_ip);
1246#else
1247		pr_retip((struct ip *)icp->icmp_data);
1248#endif
1249		break;
1250	case ICMP_ECHO:
1251		(void)printf("Echo Request\n");
1252		/* XXX ID + Seq + Data */
1253		break;
1254	case ICMP_TIMXCEED:
1255		switch(icp->icmp_code) {
1256		case ICMP_TIMXCEED_INTRANS:
1257			(void)printf("Time to live exceeded\n");
1258			break;
1259		case ICMP_TIMXCEED_REASS:
1260			(void)printf("Frag reassembly time exceeded\n");
1261			break;
1262		default:
1263			(void)printf("Time exceeded, Bad Code: %d\n",
1264			    icp->icmp_code);
1265			break;
1266		}
1267#ifndef icmp_data
1268		pr_retip(&icp->icmp_ip);
1269#else
1270		pr_retip((struct ip *)icp->icmp_data);
1271#endif
1272		break;
1273	case ICMP_PARAMPROB:
1274		(void)printf("Parameter problem: pointer = 0x%02x\n",
1275		    icp->icmp_hun.ih_pptr);
1276#ifndef icmp_data
1277		pr_retip(&icp->icmp_ip);
1278#else
1279		pr_retip((struct ip *)icp->icmp_data);
1280#endif
1281		break;
1282	case ICMP_TSTAMP:
1283		(void)printf("Timestamp\n");
1284		/* XXX ID + Seq + 3 timestamps */
1285		break;
1286	case ICMP_TSTAMPREPLY:
1287		(void)printf("Timestamp Reply\n");
1288		/* XXX ID + Seq + 3 timestamps */
1289		break;
1290	case ICMP_IREQ:
1291		(void)printf("Information Request\n");
1292		/* XXX ID + Seq */
1293		break;
1294	case ICMP_IREQREPLY:
1295		(void)printf("Information Reply\n");
1296		/* XXX ID + Seq */
1297		break;
1298	case ICMP_MASKREQ:
1299		(void)printf("Address Mask Request\n");
1300		break;
1301	case ICMP_MASKREPLY:
1302		(void)printf("Address Mask Reply\n");
1303		break;
1304	case ICMP_ROUTERADVERT:
1305		(void)printf("Router Advertisement\n");
1306		break;
1307	case ICMP_ROUTERSOLICIT:
1308		(void)printf("Router Solicitation\n");
1309		break;
1310	default:
1311		(void)printf("Bad ICMP type: %d\n", icp->icmp_type);
1312	}
1313}
1314
1315/*
1316 * pr_iph --
1317 *	Print an IP header with options.
1318 */
1319static void
1320pr_iph(ip)
1321	struct ip *ip;
1322{
1323	int hlen;
1324	u_char *cp;
1325
1326	hlen = ip->ip_hl << 2;
1327	cp = (u_char *)ip + 20;		/* point to options */
1328
1329	(void)printf("Vr HL TOS  Len   ID Flg  off TTL Pro  cks      Src      Dst\n");
1330	(void)printf(" %1x  %1x  %02x %04x %04x",
1331	    ip->ip_v, ip->ip_hl, ip->ip_tos, ntohs(ip->ip_len),
1332	    ntohs(ip->ip_id));
1333	(void)printf("   %1lx %04lx",
1334	    (u_long) (ntohl(ip->ip_off) & 0xe000) >> 13,
1335	    (u_long) ntohl(ip->ip_off) & 0x1fff);
1336	(void)printf("  %02x  %02x %04x", ip->ip_ttl, ip->ip_p,
1337							    ntohs(ip->ip_sum));
1338	(void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_src.s_addr));
1339	(void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_dst.s_addr));
1340	/* dump any option bytes */
1341	while (hlen-- > 20) {
1342		(void)printf("%02x", *cp++);
1343	}
1344	(void)putchar('\n');
1345}
1346
1347/*
1348 * pr_addr --
1349 *	Return an ascii host address as a dotted quad and optionally with
1350 * a hostname.
1351 */
1352static char *
1353pr_addr(ina)
1354	struct in_addr ina;
1355{
1356	struct hostent *hp;
1357	static char buf[16 + 3 + MAXHOSTNAMELEN];
1358
1359	if ((options & F_NUMERIC) ||
1360	    !(hp = gethostbyaddr((char *)&ina, 4, AF_INET)))
1361		return inet_ntoa(ina);
1362	else
1363		(void)snprintf(buf, sizeof(buf), "%s (%s)", hp->h_name,
1364		    inet_ntoa(ina));
1365	return(buf);
1366}
1367
1368/*
1369 * pr_retip --
1370 *	Dump some info on a returned (via ICMP) IP packet.
1371 */
1372static void
1373pr_retip(ip)
1374	struct ip *ip;
1375{
1376	int hlen;
1377	u_char *cp;
1378
1379	pr_iph(ip);
1380	hlen = ip->ip_hl << 2;
1381	cp = (u_char *)ip + hlen;
1382
1383	if (ip->ip_p == 6)
1384		(void)printf("TCP: from port %u, to port %u (decimal)\n",
1385		    (*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3)));
1386	else if (ip->ip_p == 17)
1387		(void)printf("UDP: from port %u, to port %u (decimal)\n",
1388			(*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3)));
1389}
1390
1391static void
1392fill(bp, patp)
1393	char *bp, *patp;
1394{
1395	register int ii, jj, kk;
1396	int pat[16];
1397	char *cp;
1398
1399	for (cp = patp; *cp; cp++) {
1400		if (!isxdigit(*cp))
1401			errx(EX_USAGE,
1402			     "patterns must be specified as hex digits");
1403
1404	}
1405	ii = sscanf(patp,
1406	    "%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x",
1407	    &pat[0], &pat[1], &pat[2], &pat[3], &pat[4], &pat[5], &pat[6],
1408	    &pat[7], &pat[8], &pat[9], &pat[10], &pat[11], &pat[12],
1409	    &pat[13], &pat[14], &pat[15]);
1410
1411	if (ii > 0)
1412		for (kk = 0;
1413		    kk <= MAXPACKET - (8 + PHDR_LEN + ii);
1414		    kk += ii)
1415			for (jj = 0; jj < ii; ++jj)
1416				bp[jj + kk] = pat[jj];
1417	if (!(options & F_QUIET)) {
1418		(void)printf("PATTERN: 0x");
1419		for (jj = 0; jj < ii; ++jj)
1420			(void)printf("%02x", bp[jj] & 0xFF);
1421		(void)printf("\n");
1422	}
1423}
1424
1425static void
1426usage()
1427{
1428	fprintf(stderr, "%s\n%s\n%s\n",
1429"usage: ping [-QRadfnqrv] [-c count] [-i wait] [-l preload] [-m ttl]",
1430"            [-p pattern] "
1431#ifdef IPSEC
1432#ifdef IPSEC_POLICY_IPSEC
1433"[-P policy] "
1434#endif
1435#endif
1436"[-s packetsize] [-S src_addr] [-t timeout]",
1437"            [host | [-L] [-I iface] [-T ttl] mcast-group]");
1438	exit(EX_USAGE);
1439}
1440