ping.c revision 93035
11558Srgrimes/*
21558Srgrimes * Copyright (c) 1989, 1993
31558Srgrimes *	The Regents of the University of California.  All rights reserved.
41558Srgrimes *
51558Srgrimes * This code is derived from software contributed to Berkeley by
61558Srgrimes * Mike Muuss.
71558Srgrimes *
81558Srgrimes * Redistribution and use in source and binary forms, with or without
91558Srgrimes * modification, are permitted provided that the following conditions
101558Srgrimes * are met:
111558Srgrimes * 1. Redistributions of source code must retain the above copyright
121558Srgrimes *    notice, this list of conditions and the following disclaimer.
131558Srgrimes * 2. Redistributions in binary form must reproduce the above copyright
141558Srgrimes *    notice, this list of conditions and the following disclaimer in the
151558Srgrimes *    documentation and/or other materials provided with the distribution.
161558Srgrimes * 3. All advertising materials mentioning features or use of this software
171558Srgrimes *    must display the following acknowledgement:
181558Srgrimes *	This product includes software developed by the University of
191558Srgrimes *	California, Berkeley and its contributors.
201558Srgrimes * 4. Neither the name of the University nor the names of its contributors
211558Srgrimes *    may be used to endorse or promote products derived from this software
221558Srgrimes *    without specific prior written permission.
231558Srgrimes *
241558Srgrimes * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
251558Srgrimes * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
261558Srgrimes * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
271558Srgrimes * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
281558Srgrimes * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
291558Srgrimes * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
301558Srgrimes * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
311558Srgrimes * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
321558Srgrimes * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
331558Srgrimes * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
341558Srgrimes * SUCH DAMAGE.
351558Srgrimes */
361558Srgrimes
371558Srgrimes#ifndef lint
3823247Swollmanstatic const char copyright[] =
391558Srgrimes"@(#) Copyright (c) 1989, 1993\n\
401558Srgrimes	The Regents of the University of California.  All rights reserved.\n";
411558Srgrimes#endif /* not lint */
421558Srgrimes
431558Srgrimes#ifndef lint
4437671Scharnier#if 0
451558Srgrimesstatic char sccsid[] = "@(#)ping.c	8.1 (Berkeley) 6/5/93";
4637671Scharnier#endif
4723247Swollmanstatic const char rcsid[] =
4850476Speter  "$FreeBSD: head/sbin/ping/ping.c 93035 2002-03-23 18:10:59Z obrien $";
491558Srgrimes#endif /* not lint */
501558Srgrimes
511558Srgrimes/*
521558Srgrimes *			P I N G . C
531558Srgrimes *
5437671Scharnier * Using the Internet Control Message Protocol (ICMP) "ECHO" facility,
551558Srgrimes * measure round-trip-delays and packet loss across network paths.
561558Srgrimes *
571558Srgrimes * Author -
581558Srgrimes *	Mike Muuss
591558Srgrimes *	U. S. Army Ballistic Research Laboratory
601558Srgrimes *	December, 1983
611558Srgrimes *
621558Srgrimes * Status -
631558Srgrimes *	Public Domain.  Distribution Unlimited.
641558Srgrimes * Bugs -
651558Srgrimes *	More statistics could always be gathered.
661558Srgrimes *	This program has to run SUID to ROOT to access the ICMP socket.
671558Srgrimes */
681558Srgrimes
6923247Swollman#include <sys/param.h>		/* NB: we rely on this for <sys/types.h> */
7023247Swollman
7123247Swollman#include <ctype.h>
7223247Swollman#include <err.h>
7323247Swollman#include <errno.h>
7427508Swollman#include <math.h>
7523247Swollman#include <netdb.h>
7623247Swollman#include <signal.h>
7723247Swollman#include <stdio.h>
7823247Swollman#include <stdlib.h>
7923247Swollman#include <string.h>
8023247Swollman#include <sysexits.h>
8123247Swollman#include <termios.h>
8223247Swollman#include <unistd.h>
8323247Swollman
841558Srgrimes#include <sys/socket.h>
851558Srgrimes#include <sys/time.h>
8636378Sfenner#include <sys/uio.h>
871558Srgrimes
8823247Swollman#include <netinet/in.h>
891558Srgrimes#include <netinet/in_systm.h>
901558Srgrimes#include <netinet/ip.h>
911558Srgrimes#include <netinet/ip_icmp.h>
921558Srgrimes#include <netinet/ip_var.h>
9323247Swollman#include <arpa/inet.h>
941558Srgrimes
9555505Sshin#ifdef IPSEC
9655505Sshin#include <netinet6/ipsec.h>
9755505Sshin#endif /*IPSEC*/
9855505Sshin
9936089Sjb#define	PHDR_LEN	sizeof(struct timeval)
10036089Sjb#define	DEFDATALEN	(64 - PHDR_LEN)	/* default data length */
10127533Sbde#define	FLOOD_BACKOFF	20000		/* usecs to back off if F_FLOOD mode */
10227533Sbde					/* runs out of buffer space */
1031558Srgrimes#define	MAXIPLEN	60
1041558Srgrimes#define	MAXICMPLEN	76
1051558Srgrimes#define	MAXPACKET	(65536 - 60 - 8)/* max packet size */
1061558Srgrimes#define	MAXWAIT		10		/* max seconds to wait for response */
10756342Sbillf#define	MAXALARM	(60 * 60)	/* max seconds for alarm timeout */
1081558Srgrimes#define	NROUTES		9		/* number of record route slots */
1091558Srgrimes
1101558Srgrimes#define	A(bit)		rcvd_tbl[(bit)>>3]	/* identify byte in array */
1111558Srgrimes#define	B(bit)		(1 << ((bit) & 0x07))	/* identify bit in byte */
1121558Srgrimes#define	SET(bit)	(A(bit) |= B(bit))
1131558Srgrimes#define	CLR(bit)	(A(bit) &= (~B(bit)))
1141558Srgrimes#define	TST(bit)	(A(bit) & B(bit))
1151558Srgrimes
1161558Srgrimes/* various options */
1171558Srgrimesint options;
11820540Sfenner#define	F_FLOOD		0x0001
11920540Sfenner#define	F_INTERVAL	0x0002
12020540Sfenner#define	F_NUMERIC	0x0004
12120540Sfenner#define	F_PINGFILLED	0x0008
12220540Sfenner#define	F_QUIET		0x0010
12320540Sfenner#define	F_RROUTE	0x0020
12420540Sfenner#define	F_SO_DEBUG	0x0040
12520540Sfenner#define	F_SO_DONTROUTE	0x0080
12620540Sfenner#define	F_VERBOSE	0x0100
12720540Sfenner#define	F_QUIET2	0x0200
12820540Sfenner#define	F_NOLOOP	0x0400
12920540Sfenner#define	F_MTTL		0x0800
13020540Sfenner#define	F_MIF		0x1000
13122417Sdanny#define	F_AUDIBLE	0x2000
13255505Sshin#ifdef IPSEC
13355505Sshin#ifdef IPSEC_POLICY_IPSEC
13455505Sshin#define F_POLICY	0x4000
13555505Sshin#endif /*IPSEC_POLICY_IPSEC*/
13655505Sshin#endif /*IPSEC*/
13774029Sru#define	F_TTL		0x8000
13877119Sphk#define	F_MISSED	0x10000
1391558Srgrimes
1401558Srgrimes/*
1411558Srgrimes * MAX_DUP_CHK is the number of bits in received table, i.e. the maximum
1421558Srgrimes * number of received sequence numbers we can keep track of.  Change 128
1431558Srgrimes * to 8192 for complete accuracy...
1441558Srgrimes */
1451558Srgrimes#define	MAX_DUP_CHK	(8 * 128)
1461558Srgrimesint mx_dup_ck = MAX_DUP_CHK;
1471558Srgrimeschar rcvd_tbl[MAX_DUP_CHK / 8];
1481558Srgrimes
14979403Smjacobstruct sockaddr_in whereto;	/* who to ping */
1501558Srgrimesint datalen = DEFDATALEN;
1511558Srgrimesint s;				/* socket file descriptor */
1521558Srgrimesu_char outpack[MAXPACKET];
1531558Srgrimeschar BSPACE = '\b';		/* characters written for flood */
15477119Sphkchar BBELL = '\a';		/* characters written for MISSED and AUDIBLE */
1551558Srgrimeschar DOT = '.';
1561558Srgrimeschar *hostname;
15742337Simpchar *shostname;
1581558Srgrimesint ident;			/* process id to identify our packets */
15923295Simpint uid;			/* cached uid for micro-optimization */
1601558Srgrimes
1611558Srgrimes/* counters */
1621558Srgrimeslong npackets;			/* max packets to transmit */
1631558Srgrimeslong nreceived;			/* # of packets we got back */
1641558Srgrimeslong nrepeats;			/* number of duplicates */
1651558Srgrimeslong ntransmitted;		/* sequence # for outbound packets = #sent */
16683940Siedowselong nmissedmax;		/* max value of ntransmitted - nreceived - 1 */
16738549Sdillonint interval = 1000;		/* interval between packets, ms */
1681558Srgrimes
1691558Srgrimes/* timing */
1701558Srgrimesint timing;			/* flag to do timing */
1711558Srgrimesdouble tmin = 999999999.0;	/* minimum round trip time */
1721558Srgrimesdouble tmax = 0.0;		/* maximum round trip time */
1731558Srgrimesdouble tsum = 0.0;		/* sum of all times, for doing average */
17427508Swollmandouble tsumsq = 0.0;		/* sum of all times squared, for std. dev. */
1751558Srgrimes
17627533Sbdevolatile sig_atomic_t finish_up;  /* nonzero if we've been told to finish up */
1773792Ssefint reset_kerninfo;
17827533Sbdevolatile sig_atomic_t siginfo_p;
1793792Ssef
18023247Swollmanstatic void fill(char *, char *);
18123247Swollmanstatic u_short in_cksum(u_short *, int);
18223247Swollmanstatic void check_status(void);
18327533Sbdestatic void finish(void) __dead2;
18423247Swollmanstatic void pinger(void);
18523247Swollmanstatic char *pr_addr(struct in_addr);
18623247Swollmanstatic void pr_icmph(struct icmp *);
18723247Swollmanstatic void pr_iph(struct ip *);
18836378Sfennerstatic void pr_pack(char *, int, struct sockaddr_in *, struct timeval *);
18923247Swollmanstatic void pr_retip(struct ip *);
19023247Swollmanstatic void status(int);
19127533Sbdestatic void stopit(int);
19223247Swollmanstatic void tvsub(struct timeval *, struct timeval *);
19337671Scharnierstatic void usage(void) __dead2;
1941558Srgrimes
19523247Swollmanint
1961558Srgrimesmain(argc, argv)
1971558Srgrimes	int argc;
19823247Swollman	char *const *argv;
1991558Srgrimes{
20093035Sobrien	struct in_addr ifaddr;
20193035Sobrien	struct iovec iov;
20293035Sobrien	struct msghdr msg;
20393035Sobrien	struct sigaction si_sa;
20493035Sobrien	struct sockaddr_in from, sin;
20593035Sobrien	struct termios ts;
20636378Sfenner	struct timeval last, intvl;
2071558Srgrimes	struct hostent *hp;
20893035Sobrien	struct sockaddr_in *to;
2091558Srgrimes	u_char *datap, *packet;
21093035Sobrien	char *ep, *source, *target;
21193035Sobrien#ifdef IPSEC_POLICY_IPSEC
21293035Sobrien	char *policy_in, *policy_out;
21393035Sobrien#endif
21493035Sobrien	u_long alarmtimeout, ultmp;
21593035Sobrien	int ch, hold, i, packlen, preload, sockerrno, almost_done = 0, ttl;
21693035Sobrien	char ctrl[CMSG_SPACE(sizeof(struct timeval))];
21793035Sobrien	char hnamebuf[MAXHOSTNAMELEN], snamebuf[MAXHOSTNAMELEN];
2181558Srgrimes#ifdef IP_OPTIONS
2191558Srgrimes	char rspace[3 + 4 * NROUTES + 1];	/* record route space */
2201558Srgrimes#endif
22193035Sobrien	unsigned char mttl, loop;
22293035Sobrien
22393035Sobrien	source = NULL;
22455505Sshin#ifdef IPSEC_POLICY_IPSEC
22593035Sobrien	policy_in = policy_out = NULL;
22655505Sshin#endif
2271558Srgrimes
22817474Sfenner	/*
22917474Sfenner	 * Do the stuff that we need root priv's for *first*, and
23017474Sfenner	 * then drop our setuid bit.  Save error reporting for
23117474Sfenner	 * after arg parsing.
23217474Sfenner	 */
23323247Swollman	s = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
23423247Swollman	sockerrno = errno;
23517474Sfenner
23617474Sfenner	setuid(getuid());
23723295Simp	uid = getuid();
23817474Sfenner
23956342Sbillf	alarmtimeout = preload = 0;
2403792Ssef
24136089Sjb	datap = &outpack[8 + PHDR_LEN];
24274029Sru	while ((ch = getopt(argc, argv,
24377119Sphk		"AI:LQRS:T:c:adfi:l:m:np:qrs:t:v"
24474029Sru#ifdef IPSEC
24555505Sshin#ifdef IPSEC_POLICY_IPSEC
24674029Sru		"P:"
24755505Sshin#endif /*IPSEC_POLICY_IPSEC*/
24874029Sru#endif /*IPSEC*/
24974029Sru		)) != -1)
25055505Sshin	{
2511558Srgrimes		switch(ch) {
25277119Sphk		case 'A':
25377119Sphk			options |= F_MISSED;
25477119Sphk			break;
25522417Sdanny		case 'a':
25622417Sdanny			options |= F_AUDIBLE;
25722417Sdanny			break;
2581558Srgrimes		case 'c':
25923247Swollman			ultmp = strtoul(optarg, &ep, 0);
26023247Swollman			if (*ep || ep == optarg || ultmp > LONG_MAX || !ultmp)
26123247Swollman				errx(EX_USAGE,
26223247Swollman				    "invalid count of packets to transmit: `%s'",
26323247Swollman				    optarg);
26423247Swollman			npackets = ultmp;
2651558Srgrimes			break;
2661558Srgrimes		case 'd':
2671558Srgrimes			options |= F_SO_DEBUG;
2681558Srgrimes			break;
2691558Srgrimes		case 'f':
27038549Sdillon			if (uid) {
27123247Swollman				errno = EPERM;
27223247Swollman				err(EX_NOPERM, "-f flag");
2731558Srgrimes			}
2741558Srgrimes			options |= F_FLOOD;
2751558Srgrimes			setbuf(stdout, (char *)NULL);
2761558Srgrimes			break;
2771558Srgrimes		case 'i':		/* wait between sending packets */
27838549Sdillon			{
27938549Sdillon			    double t = strtod(optarg, &ep) * 1000.0;
28038549Sdillon
28138549Sdillon			    if (*ep || ep == optarg || t > (double)INT_MAX) {
28238549Sdillon				    errx(
28338549Sdillon					    EX_USAGE,
28438549Sdillon					     "invalid timing interval: `%s'",
28538549Sdillon					     optarg
28638549Sdillon				    );
28738549Sdillon			    }
28838549Sdillon			    options |= F_INTERVAL;
28938549Sdillon			    interval = (int)t;
29038549Sdillon			    if (uid && interval < 1000) {
29138549Sdillon				    errno = EPERM;
29238549Sdillon				    err(EX_NOPERM, "-i interval too short");
29338549Sdillon			    }
29438549Sdillon			}
2951558Srgrimes			break;
29620540Sfenner		case 'I':		/* multicast interface */
29723247Swollman			if (inet_aton(optarg, &ifaddr) == 0)
29823247Swollman				errx(EX_USAGE,
29923247Swollman				     "invalid multicast interface: `%s'",
30023247Swollman				     optarg);
30120540Sfenner			options |= F_MIF;
30220540Sfenner			break;
3031558Srgrimes		case 'l':
30423247Swollman			ultmp = strtoul(optarg, &ep, 0);
30523247Swollman			if (*ep || ep == optarg || ultmp > INT_MAX)
30623247Swollman				errx(EX_USAGE,
30723247Swollman				     "invalid preload value: `%s'", optarg);
30846643Smckay			if (uid) {
30923251Simp				errno = EPERM;
31023251Simp				err(EX_NOPERM, "-l flag");
31123251Simp			}
31223247Swollman			preload = ultmp;
3131558Srgrimes			break;
31420540Sfenner		case 'L':
31520540Sfenner			options |= F_NOLOOP;
31620540Sfenner			loop = 0;
31720540Sfenner			break;
31874029Sru		case 'm':		/* TTL */
31974029Sru			ultmp = strtoul(optarg, &ep, 0);
32074029Sru			if (*ep || ep == optarg || ultmp > 255)
32174029Sru				errx(EX_USAGE, "invalid TTL: `%s'",
32274029Sru				     optarg);
32374029Sru			ttl = ultmp;
32474029Sru			options |= F_TTL;
32574029Sru			break;
3261558Srgrimes		case 'n':
3271558Srgrimes			options |= F_NUMERIC;
3281558Srgrimes			break;
3291558Srgrimes		case 'p':		/* fill buffer with user pattern */
3301558Srgrimes			options |= F_PINGFILLED;
3311558Srgrimes			fill((char *)datap, optarg);
3321558Srgrimes				break;
33317724Sfenner		case 'Q':
33417724Sfenner			options |= F_QUIET2;
33517724Sfenner			break;
3361558Srgrimes		case 'q':
3371558Srgrimes			options |= F_QUIET;
3381558Srgrimes			break;
3391558Srgrimes		case 'R':
3401558Srgrimes			options |= F_RROUTE;
3411558Srgrimes			break;
3421558Srgrimes		case 'r':
3431558Srgrimes			options |= F_SO_DONTROUTE;
3441558Srgrimes			break;
3451558Srgrimes		case 's':		/* size of packet to send */
34638549Sdillon			if (uid) {
34738549Sdillon				errno = EPERM;
34838549Sdillon				err(EX_NOPERM, "-s flag");
34938549Sdillon			}
35023247Swollman			ultmp = strtoul(optarg, &ep, 0);
35123247Swollman			if (ultmp > MAXPACKET)
35223247Swollman				errx(EX_USAGE, "packet size too large: %lu",
35323247Swollman				     ultmp);
35423247Swollman			if (*ep || ep == optarg || !ultmp)
35523247Swollman				errx(EX_USAGE, "invalid packet size: `%s'",
35623247Swollman				     optarg);
35723247Swollman			datalen = ultmp;
3581558Srgrimes			break;
35942337Simp		case 'S':
36042337Simp			source = optarg;
36142337Simp			break;
36255996Sbillf		case 't':
36356342Sbillf			alarmtimeout = strtoul(optarg, &ep, 0);
36456342Sbillf			if ((alarmtimeout < 1) || (alarmtimeout == ULONG_MAX))
36555996Sbillf				errx(EX_USAGE, "invalid timeout: `%s'",
36655996Sbillf				    optarg);
36756342Sbillf			if (alarmtimeout > MAXALARM)
36856342Sbillf				errx(EX_USAGE, "invalid timeout: `%s' > %d",
36956342Sbillf				    optarg, MAXALARM);
37056342Sbillf			alarm((int)alarmtimeout);
37155996Sbillf			break;
37220540Sfenner		case 'T':		/* multicast TTL */
37323247Swollman			ultmp = strtoul(optarg, &ep, 0);
37423247Swollman			if (*ep || ep == optarg || ultmp > 255)
37523247Swollman				errx(EX_USAGE, "invalid multicast TTL: `%s'",
37623247Swollman				     optarg);
37774029Sru			mttl = ultmp;
37820540Sfenner			options |= F_MTTL;
37920540Sfenner			break;
3801558Srgrimes		case 'v':
3811558Srgrimes			options |= F_VERBOSE;
3821558Srgrimes			break;
38355505Sshin#ifdef IPSEC
38455505Sshin#ifdef IPSEC_POLICY_IPSEC
38555505Sshin		case 'P':
38655505Sshin			options |= F_POLICY;
38755505Sshin			if (!strncmp("in", optarg, 2))
38855505Sshin				policy_in = strdup(optarg);
38955505Sshin			else if (!strncmp("out", optarg, 3))
39055505Sshin				policy_out = strdup(optarg);
39155505Sshin			else
39255505Sshin				errx(1, "invalid security policy");
39355505Sshin			break;
39455505Sshin#endif /*IPSEC_POLICY_IPSEC*/
39555505Sshin#endif /*IPSEC*/
3961558Srgrimes		default:
39737671Scharnier			usage();
3981558Srgrimes		}
39923247Swollman	}
4001558Srgrimes
40123247Swollman	if (argc - optind != 1)
40237671Scharnier		usage();
40323247Swollman	target = argv[optind];
4041558Srgrimes
40542337Simp	if (source) {
40642337Simp		bzero((char *)&sin, sizeof(sin));
40742337Simp		sin.sin_family = AF_INET;
40842337Simp		if (inet_aton(source, &sin.sin_addr) != 0) {
40942337Simp			shostname = source;
41042337Simp		} else {
41142337Simp			hp = gethostbyname2(source, AF_INET);
41242337Simp			if (!hp)
41342337Simp				errx(EX_NOHOST, "cannot resolve %s: %s",
41442337Simp				     source, hstrerror(h_errno));
41542337Simp
41642337Simp			sin.sin_len = sizeof sin;
41742337Simp			if (hp->h_length > sizeof(sin.sin_addr))
41842337Simp				errx(1,"gethostbyname2: illegal address");
41942337Simp			memcpy(&sin.sin_addr, hp->h_addr_list[0],
42042337Simp				sizeof (sin.sin_addr));
42142337Simp			(void)strncpy(snamebuf, hp->h_name,
42242337Simp				sizeof(snamebuf) - 1);
42342337Simp			snamebuf[sizeof(snamebuf) - 1] = '\0';
42442337Simp			shostname = snamebuf;
42542337Simp		}
42642337Simp		if (bind(s, (struct sockaddr *)&sin, sizeof sin) == -1)
42742337Simp			err(1, "bind");
42842337Simp	}
42942337Simp
43079403Smjacob	bzero(&whereto, sizeof(whereto));
43179403Smjacob	to = &whereto;
4321558Srgrimes	to->sin_family = AF_INET;
43379403Smjacob	to->sin_len = sizeof *to;
43423247Swollman	if (inet_aton(target, &to->sin_addr) != 0) {
4351558Srgrimes		hostname = target;
43623247Swollman	} else {
43723247Swollman		hp = gethostbyname2(target, AF_INET);
43823247Swollman		if (!hp)
43923247Swollman			errx(EX_NOHOST, "cannot resolve %s: %s",
44023247Swollman			     target, hstrerror(h_errno));
44123247Swollman
44223327Simp		if (hp->h_length > sizeof(to->sin_addr))
44323327Simp			errx(1,"gethostbyname2 returned an illegal address");
44423247Swollman		memcpy(&to->sin_addr, hp->h_addr_list[0], sizeof to->sin_addr);
4451558Srgrimes		(void)strncpy(hnamebuf, hp->h_name, sizeof(hnamebuf) - 1);
44631956Simp		hnamebuf[sizeof(hnamebuf) - 1] = '\0';
4471558Srgrimes		hostname = hnamebuf;
4481558Srgrimes	}
4491558Srgrimes
45023247Swollman	if (options & F_FLOOD && options & F_INTERVAL)
45123247Swollman		errx(EX_USAGE, "-f and -i: incompatible options");
4521558Srgrimes
45323247Swollman	if (options & F_FLOOD && IN_MULTICAST(ntohl(to->sin_addr.s_addr)))
45423247Swollman		errx(EX_USAGE,
45523247Swollman		     "-f flag cannot be used with multicast destination");
45623247Swollman	if (options & (F_MIF | F_NOLOOP | F_MTTL)
45723247Swollman	    && !IN_MULTICAST(ntohl(to->sin_addr.s_addr)))
45823247Swollman		errx(EX_USAGE,
45923247Swollman		     "-I, -L, -T flags cannot be used with unicast destination");
46023247Swollman
46136089Sjb	if (datalen >= PHDR_LEN)	/* can we time transfer */
4621558Srgrimes		timing = 1;
4631558Srgrimes	packlen = datalen + MAXIPLEN + MAXICMPLEN;
46423247Swollman	if (!(packet = (u_char *)malloc((size_t)packlen)))
46523247Swollman		err(EX_UNAVAILABLE, "malloc");
46623247Swollman
4671558Srgrimes	if (!(options & F_PINGFILLED))
46836089Sjb		for (i = PHDR_LEN; i < datalen; ++i)
4691558Srgrimes			*datap++ = i;
4701558Srgrimes
4711558Srgrimes	ident = getpid() & 0xFFFF;
4721558Srgrimes
47317474Sfenner	if (s < 0) {
47417474Sfenner		errno = sockerrno;
47523247Swollman		err(EX_OSERR, "socket");
4761558Srgrimes	}
4771558Srgrimes	hold = 1;
4781558Srgrimes	if (options & F_SO_DEBUG)
4791558Srgrimes		(void)setsockopt(s, SOL_SOCKET, SO_DEBUG, (char *)&hold,
4801558Srgrimes		    sizeof(hold));
4811558Srgrimes	if (options & F_SO_DONTROUTE)
4821558Srgrimes		(void)setsockopt(s, SOL_SOCKET, SO_DONTROUTE, (char *)&hold,
4831558Srgrimes		    sizeof(hold));
48455505Sshin#ifdef IPSEC
48555505Sshin#ifdef IPSEC_POLICY_IPSEC
48655505Sshin	if (options & F_POLICY) {
48755505Sshin		char *buf;
48855505Sshin		if (policy_in != NULL) {
48955505Sshin			buf = ipsec_set_policy(policy_in, strlen(policy_in));
49055505Sshin			if (buf == NULL)
49168905Skris				errx(EX_CONFIG, "%s", ipsec_strerror());
49255505Sshin			if (setsockopt(s, IPPROTO_IP, IP_IPSEC_POLICY,
49355505Sshin					buf, ipsec_get_policylen(buf)) < 0)
49455505Sshin				err(EX_CONFIG, "ipsec policy cannot be configured");
49555505Sshin			free(buf);
49655505Sshin		}
4971558Srgrimes
49855505Sshin		if (policy_out != NULL) {
49955505Sshin			buf = ipsec_set_policy(policy_out, strlen(policy_out));
50055505Sshin			if (buf == NULL)
50168905Skris				errx(EX_CONFIG, "%s", ipsec_strerror());
50255505Sshin			if (setsockopt(s, IPPROTO_IP, IP_IPSEC_POLICY,
50355505Sshin					buf, ipsec_get_policylen(buf)) < 0)
50455505Sshin				err(EX_CONFIG, "ipsec policy cannot be configured");
50555505Sshin			free(buf);
50655505Sshin		}
50755505Sshin	}
50855505Sshin#endif /*IPSEC_POLICY_IPSEC*/
50955505Sshin#endif /*IPSEC*/
51055505Sshin
5111558Srgrimes	/* record route option */
5121558Srgrimes	if (options & F_RROUTE) {
5131558Srgrimes#ifdef IP_OPTIONS
51436378Sfenner		bzero(rspace, sizeof(rspace));
5151558Srgrimes		rspace[IPOPT_OPTVAL] = IPOPT_RR;
51636378Sfenner		rspace[IPOPT_OLEN] = sizeof(rspace) - 1;
5171558Srgrimes		rspace[IPOPT_OFFSET] = IPOPT_MINOFF;
51836378Sfenner		rspace[sizeof(rspace) - 1] = IPOPT_EOL;
5191558Srgrimes		if (setsockopt(s, IPPROTO_IP, IP_OPTIONS, rspace,
52023247Swollman		    sizeof(rspace)) < 0)
52123247Swollman			err(EX_OSERR, "setsockopt IP_OPTIONS");
5221558Srgrimes#else
52323247Swollman		errx(EX_UNAVAILABLE,
52423247Swollman		  "record route not available in this implementation");
5251558Srgrimes#endif /* IP_OPTIONS */
5261558Srgrimes	}
5271558Srgrimes
52874029Sru	if (options & F_TTL) {
52974029Sru		if (setsockopt(s, IPPROTO_IP, IP_TTL, &ttl,
53074029Sru		    sizeof(ttl)) < 0) {
53174029Sru			err(EX_OSERR, "setsockopt IP_TTL");
53274029Sru		}
53374029Sru	}
53420540Sfenner	if (options & F_NOLOOP) {
53520540Sfenner		if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_LOOP, &loop,
53620540Sfenner		    sizeof(loop)) < 0) {
53723247Swollman			err(EX_OSERR, "setsockopt IP_MULTICAST_LOOP");
53820540Sfenner		}
53920540Sfenner	}
54020540Sfenner	if (options & F_MTTL) {
54174029Sru		if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL, &mttl,
54274029Sru		    sizeof(mttl)) < 0) {
54323247Swollman			err(EX_OSERR, "setsockopt IP_MULTICAST_TTL");
54420540Sfenner		}
54520540Sfenner	}
54620540Sfenner	if (options & F_MIF) {
54720540Sfenner		if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_IF, &ifaddr,
54820540Sfenner		    sizeof(ifaddr)) < 0) {
54923247Swollman			err(EX_OSERR, "setsockopt IP_MULTICAST_IF");
55020540Sfenner		}
55120540Sfenner	}
55236378Sfenner#ifdef SO_TIMESTAMP
55336378Sfenner	{ int on = 1;
55436378Sfenner	if (setsockopt(s, SOL_SOCKET, SO_TIMESTAMP, &on, sizeof(on)) < 0)
55536378Sfenner		err(EX_OSERR, "setsockopt SO_TIMESTAMP");
55636378Sfenner	}
55736378Sfenner#endif
55820540Sfenner
5591558Srgrimes	/*
5601558Srgrimes	 * When pinging the broadcast address, you can get a lot of answers.
5611558Srgrimes	 * Doing something so evil is useful if you are trying to stress the
5621558Srgrimes	 * ethernet, or just want to fill the arp cache to get some stuff for
56323247Swollman	 * /etc/ethers.  But beware: RFC 1122 allows hosts to ignore broadcast
56423247Swollman	 * or multicast pings if they wish.
5651558Srgrimes	 */
5661558Srgrimes	hold = 48 * 1024;
5671558Srgrimes	(void)setsockopt(s, SOL_SOCKET, SO_RCVBUF, (char *)&hold,
5681558Srgrimes	    sizeof(hold));
5691558Srgrimes
57079018Srwatson	if (!uid) {
57179018Srwatson		(void)setsockopt(s, SOL_SOCKET, SO_SNDBUF, (char *)&hold,
57279018Srwatson		    sizeof(hold));
57379018Srwatson	}
57479018Srwatson
57542337Simp	if (to->sin_family == AF_INET) {
57642337Simp		(void)printf("PING %s (%s)", hostname,
57742337Simp		    inet_ntoa(to->sin_addr));
57842337Simp		if (source)
57942337Simp			(void)printf(" from %s", shostname);
58042337Simp		(void)printf(": %d data bytes\n", datalen);
58142337Simp	} else
5821558Srgrimes		(void)printf("PING %s: %d data bytes\n", hostname, datalen);
5831558Srgrimes
58420280Sbde	/*
58527354Ssef	 * Use sigaction() instead of signal() to get unambiguous semantics,
58627354Ssef	 * in particular with SA_RESTART not set.
58720280Sbde	 */
58827354Ssef
58920205Spst	sigemptyset(&si_sa.sa_mask);
59020195Ssef	si_sa.sa_flags = 0;
59127354Ssef
59227354Ssef	si_sa.sa_handler = stopit;
59327354Ssef	if (sigaction(SIGINT, &si_sa, 0) == -1) {
59427354Ssef		err(EX_OSERR, "sigaction SIGINT");
59527354Ssef	}
59627354Ssef
59727354Ssef	si_sa.sa_handler = status;
59820195Ssef	if (sigaction(SIGINFO, &si_sa, 0) == -1) {
59923385Simp		err(EX_OSERR, "sigaction");
60020195Ssef	}
60120195Ssef
60256342Sbillf        if (alarmtimeout > 0) {
60356342Sbillf		si_sa.sa_handler = stopit;
60456342Sbillf		if (sigaction(SIGALRM, &si_sa, 0) == -1)
60556342Sbillf			err(EX_OSERR, "sigaction SIGALRM");
60656342Sbillf        }
60756342Sbillf
60836378Sfenner	bzero(&msg, sizeof(msg));
60936378Sfenner	msg.msg_name = (caddr_t)&from;
61036378Sfenner	msg.msg_iov = &iov;
61136378Sfenner	msg.msg_iovlen = 1;
61236378Sfenner#ifdef SO_TIMESTAMP
61336378Sfenner	msg.msg_control = (caddr_t)ctrl;
61436378Sfenner#endif
61536378Sfenner	iov.iov_base = packet;
61636378Sfenner	iov.iov_len = packlen;
61736378Sfenner
61819864Ssef	if (tcgetattr(STDOUT_FILENO, &ts) != -1) {
61919864Ssef		reset_kerninfo = !(ts.c_lflag & NOKERNINFO);
62019864Ssef		ts.c_lflag |= NOKERNINFO;
62119864Ssef		tcsetattr(STDOUT_FILENO, TCSANOW, &ts);
62219864Ssef	}
62319864Ssef
62489349Sru	if (preload == 0)
62589349Sru		pinger();		/* send the first ping */
62689349Sru	else {
62789349Sru		if (npackets != 0 && preload > npackets)
62889349Sru			preload = npackets;
62989349Sru		while (preload--)	/* fire off them quickies */
63089349Sru			pinger();
63189349Sru	}
63289349Sru	(void)gettimeofday(&last, NULL);
6331558Srgrimes
63436378Sfenner	if (options & F_FLOOD) {
63536378Sfenner		intvl.tv_sec = 0;
63636378Sfenner		intvl.tv_usec = 10000;
63736378Sfenner	} else {
63838549Sdillon		intvl.tv_sec = interval / 1000;
63938549Sdillon		intvl.tv_usec = interval % 1000 * 1000;
64036378Sfenner	}
6411558Srgrimes
64227533Sbde	while (!finish_up) {
64392806Sobrien		int cc;
64436378Sfenner		int n;
64536378Sfenner		struct timeval timeout, now;
64636378Sfenner		fd_set rfds;
6471558Srgrimes
64820280Sbde		check_status();
64936378Sfenner		FD_ZERO(&rfds);
65036378Sfenner		FD_SET(s, &rfds);
65136378Sfenner		(void)gettimeofday(&now, NULL);
65236378Sfenner		timeout.tv_sec = last.tv_sec + intvl.tv_sec - now.tv_sec;
65336378Sfenner		timeout.tv_usec = last.tv_usec + intvl.tv_usec - now.tv_usec;
65436378Sfenner		while (timeout.tv_usec < 0) {
65536378Sfenner			timeout.tv_usec += 1000000;
65636378Sfenner			timeout.tv_sec--;
6571558Srgrimes		}
65837671Scharnier		while (timeout.tv_usec >= 1000000) {
65936378Sfenner			timeout.tv_usec -= 1000000;
66036378Sfenner			timeout.tv_sec++;
66136378Sfenner		}
66236378Sfenner		if (timeout.tv_sec < 0)
66336378Sfenner			timeout.tv_sec = timeout.tv_usec = 0;
66436378Sfenner		n = select(s + 1, &rfds, NULL, NULL, &timeout);
66546643Smckay		if (n < 0)
66646643Smckay			continue;	/* Must be EINTR. */
66736378Sfenner		if (n == 1) {
66836378Sfenner			struct timeval *t = 0;
66936378Sfenner#ifdef SO_TIMESTAMP
67036378Sfenner			struct cmsghdr *cmsg = (struct cmsghdr *)&ctrl;
67136378Sfenner
67236378Sfenner			msg.msg_controllen = sizeof(ctrl);
67336378Sfenner#endif
67436378Sfenner			msg.msg_namelen = sizeof(from);
67536378Sfenner			if ((cc = recvmsg(s, &msg, 0)) < 0) {
67636378Sfenner				if (errno == EINTR)
67736378Sfenner					continue;
67837671Scharnier				warn("recvmsg");
6791558Srgrimes				continue;
68036378Sfenner			}
68136378Sfenner#ifdef SO_TIMESTAMP
68236378Sfenner			if (cmsg->cmsg_level == SOL_SOCKET &&
68336378Sfenner			    cmsg->cmsg_type == SCM_TIMESTAMP &&
68458068Sshin			    cmsg->cmsg_len == CMSG_LEN(sizeof *t)) {
68536713Sjb				/* Copy to avoid alignment problems: */
68636713Sjb				memcpy(&now,CMSG_DATA(cmsg),sizeof(now));
68736713Sjb				t = &now;
68836713Sjb			}
68936378Sfenner#endif
69036378Sfenner			if (t == 0) {
69136378Sfenner				(void)gettimeofday(&now, NULL);
69236378Sfenner				t = &now;
69336378Sfenner			}
69436378Sfenner			pr_pack((char *)packet, cc, &from, t);
69536378Sfenner			if (npackets && nreceived >= npackets)
69636378Sfenner				break;
6971558Srgrimes		}
69846643Smckay		if (n == 0 || options & F_FLOOD) {
69936378Sfenner			if (!npackets || ntransmitted < npackets)
70036378Sfenner				pinger();
70136378Sfenner			else {
70236378Sfenner				if (almost_done)
70336378Sfenner					break;
70436378Sfenner				almost_done = 1;
70546643Smckay				intvl.tv_usec = 0;
70636378Sfenner				if (nreceived) {
70736378Sfenner					intvl.tv_sec = 2 * tmax / 1000;
70836378Sfenner					if (!intvl.tv_sec)
70936378Sfenner						intvl.tv_sec = 1;
71036378Sfenner				} else
71136378Sfenner					intvl.tv_sec = MAXWAIT;
71236378Sfenner			}
71336378Sfenner			(void)gettimeofday(&last, NULL);
71477119Sphk
71583940Siedowse			if (ntransmitted - nreceived - 1 > nmissedmax) {
71683940Siedowse				nmissedmax = ntransmitted - nreceived - 1;
71783940Siedowse				if (options & F_MISSED)
71883940Siedowse					(void)write(STDOUT_FILENO, &BBELL, 1);
71983940Siedowse			}
72036378Sfenner		}
7211558Srgrimes	}
72227533Sbde	finish();
7231558Srgrimes	/* NOTREACHED */
72423251Simp	exit(0);	/* Make the compiler happy */
7251558Srgrimes}
7261558Srgrimes
7271558Srgrimes/*
72827533Sbde * stopit --
72927533Sbde *	Set the global bit that causes the main loop to quit.
73027533Sbde * Do NOT call finish() from here, since finish() does far too much
73127533Sbde * to be called from a signal handler.
73227299Sjulian */
73327299Sjulianvoid
73427533Sbdestopit(sig)
73527533Sbde	int sig;
73627299Sjulian{
73793035Sobrien
73827299Sjulian	finish_up = 1;
73927299Sjulian}
74027299Sjulian
74127299Sjulian/*
7421558Srgrimes * pinger --
7431558Srgrimes *	Compose and transmit an ICMP ECHO REQUEST packet.  The IP packet
7441558Srgrimes * will be added on by the kernel.  The ID field is our UNIX process ID,
7451558Srgrimes * and the sequence number is an ascending integer.  The first 8 bytes
74617724Sfenner * of the data portion are used to hold a UNIX "timeval" struct in host
7471558Srgrimes * byte-order, to compute the round-trip time.
7481558Srgrimes */
74923247Swollmanstatic void
75023247Swollmanpinger(void)
7511558Srgrimes{
75292806Sobrien	struct icmp *icp;
75393035Sobrien	int cc, i;
7541558Srgrimes
7551558Srgrimes	icp = (struct icmp *)outpack;
7561558Srgrimes	icp->icmp_type = ICMP_ECHO;
7571558Srgrimes	icp->icmp_code = 0;
7581558Srgrimes	icp->icmp_cksum = 0;
75991432Sfenner	icp->icmp_seq = htons(ntransmitted);
7601558Srgrimes	icp->icmp_id = ident;			/* ID */
7611558Srgrimes
76291432Sfenner	CLR(ntransmitted % mx_dup_ck);
7631558Srgrimes
7641558Srgrimes	if (timing)
7651558Srgrimes		(void)gettimeofday((struct timeval *)&outpack[8],
7661558Srgrimes		    (struct timezone *)NULL);
7671558Srgrimes
76836089Sjb	cc = datalen + PHDR_LEN;		/* skips ICMP portion */
7691558Srgrimes
7701558Srgrimes	/* compute ICMP checksum here */
7711558Srgrimes	icp->icmp_cksum = in_cksum((u_short *)icp, cc);
7721558Srgrimes
77379403Smjacob	i = sendto(s, (char *)outpack, cc, 0, (struct sockaddr *)&whereto,
77479403Smjacob	    sizeof(whereto));
7751558Srgrimes
7761558Srgrimes	if (i < 0 || i != cc)  {
77723247Swollman		if (i < 0) {
77827533Sbde			if (options & F_FLOOD && errno == ENOBUFS) {
77927299Sjulian				usleep(FLOOD_BACKOFF);
78027299Sjulian				return;
78127299Sjulian			}
78223247Swollman			warn("sendto");
78323247Swollman		} else {
78423247Swollman			warn("%s: partial write: %d of %d bytes",
78535216Sphk			     hostname, i, cc);
78623247Swollman		}
78727945Sjulian	}
78827945Sjulian	ntransmitted++;
7891558Srgrimes	if (!(options & F_QUIET) && options & F_FLOOD)
7901558Srgrimes		(void)write(STDOUT_FILENO, &DOT, 1);
7911558Srgrimes}
7921558Srgrimes
7931558Srgrimes/*
7941558Srgrimes * pr_pack --
7951558Srgrimes *	Print out the packet, if it came from us.  This logic is necessary
7961558Srgrimes * because ALL readers of the ICMP socket get a copy of ALL ICMP packets
7971558Srgrimes * which arrive ('tis only fair).  This permits multiple copies of this
7981558Srgrimes * program to be run without having intermingled output (or statistics!).
7991558Srgrimes */
80023247Swollmanstatic void
80136378Sfennerpr_pack(buf, cc, from, tv)
8021558Srgrimes	char *buf;
8031558Srgrimes	int cc;
8041558Srgrimes	struct sockaddr_in *from;
80536378Sfenner	struct timeval *tv;
8061558Srgrimes{
80792806Sobrien	struct icmp *icp;
80893035Sobrien	struct ip *ip;
80993035Sobrien	struct timeval *tp;
81093035Sobrien	u_char *cp, *dp;
81193035Sobrien	double triptime;
81292806Sobrien	u_long l;
81393035Sobrien	int dupflag, hlen, i, j, seq;
8141558Srgrimes	static int old_rrlen;
8151558Srgrimes	static char old_rr[MAX_IPOPTLEN];
8161558Srgrimes
8171558Srgrimes	/* Check the IP header */
8181558Srgrimes	ip = (struct ip *)buf;
8191558Srgrimes	hlen = ip->ip_hl << 2;
8201558Srgrimes	if (cc < hlen + ICMP_MINLEN) {
8211558Srgrimes		if (options & F_VERBOSE)
82223247Swollman			warn("packet too short (%d bytes) from %s", cc,
82323247Swollman			     inet_ntoa(from->sin_addr));
8241558Srgrimes		return;
8251558Srgrimes	}
8261558Srgrimes
8271558Srgrimes	/* Now the ICMP part */
8281558Srgrimes	cc -= hlen;
8291558Srgrimes	icp = (struct icmp *)(buf + hlen);
8301558Srgrimes	if (icp->icmp_type == ICMP_ECHOREPLY) {
8311558Srgrimes		if (icp->icmp_id != ident)
8321558Srgrimes			return;			/* 'Twas not our ECHO */
8331558Srgrimes		++nreceived;
83427533Sbde		triptime = 0.0;
8351558Srgrimes		if (timing) {
83636089Sjb			struct timeval tv1;
8371558Srgrimes#ifndef icmp_data
8381558Srgrimes			tp = (struct timeval *)&icp->icmp_ip;
8391558Srgrimes#else
8401558Srgrimes			tp = (struct timeval *)icp->icmp_data;
8411558Srgrimes#endif
84236089Sjb			/* Avoid unaligned data: */
84336089Sjb			memcpy(&tv1,tp,sizeof(tv1));
84436378Sfenner			tvsub(tv, &tv1);
84536378Sfenner 			triptime = ((double)tv->tv_sec) * 1000.0 +
84636378Sfenner 			    ((double)tv->tv_usec) / 1000.0;
8471558Srgrimes			tsum += triptime;
84827508Swollman			tsumsq += triptime * triptime;
8491558Srgrimes			if (triptime < tmin)
8501558Srgrimes				tmin = triptime;
8511558Srgrimes			if (triptime > tmax)
8521558Srgrimes				tmax = triptime;
8531558Srgrimes		}
8541558Srgrimes
85591432Sfenner		seq = ntohs(icp->icmp_seq);
85691432Sfenner
85791432Sfenner		if (TST(seq % mx_dup_ck)) {
8581558Srgrimes			++nrepeats;
8591558Srgrimes			--nreceived;
8601558Srgrimes			dupflag = 1;
8611558Srgrimes		} else {
86291432Sfenner			SET(seq % mx_dup_ck);
8631558Srgrimes			dupflag = 0;
8641558Srgrimes		}
8651558Srgrimes
8661558Srgrimes		if (options & F_QUIET)
8671558Srgrimes			return;
8681558Srgrimes
8691558Srgrimes		if (options & F_FLOOD)
8701558Srgrimes			(void)write(STDOUT_FILENO, &BSPACE, 1);
8711558Srgrimes		else {
8721558Srgrimes			(void)printf("%d bytes from %s: icmp_seq=%u", cc,
8731558Srgrimes			   inet_ntoa(*(struct in_addr *)&from->sin_addr.s_addr),
87491432Sfenner			   seq);
8751558Srgrimes			(void)printf(" ttl=%d", ip->ip_ttl);
8761558Srgrimes			if (timing)
8771859Sdg				(void)printf(" time=%.3f ms", triptime);
8781558Srgrimes			if (dupflag)
8791558Srgrimes				(void)printf(" (DUP!)");
88022417Sdanny			if (options & F_AUDIBLE)
88177119Sphk				(void)write(STDOUT_FILENO, &BBELL, 1);
8821558Srgrimes			/* check the data */
88336089Sjb			cp = (u_char*)&icp->icmp_data[PHDR_LEN];
88436089Sjb			dp = &outpack[8 + PHDR_LEN];
88536089Sjb			for (i = PHDR_LEN; i < datalen; ++i, ++cp, ++dp) {
8861558Srgrimes				if (*cp != *dp) {
8871558Srgrimes	(void)printf("\nwrong data byte #%d should be 0x%x but was 0x%x",
8881558Srgrimes	    i, *dp, *cp);
88936089Sjb					printf("\ncp:");
8901558Srgrimes					cp = (u_char*)&icp->icmp_data[0];
89136089Sjb					for (i = 0; i < datalen; ++i, ++cp) {
8921558Srgrimes						if ((i % 32) == 8)
8931558Srgrimes							(void)printf("\n\t");
8941558Srgrimes						(void)printf("%x ", *cp);
8951558Srgrimes					}
89636089Sjb					printf("\ndp:");
89736089Sjb					cp = &outpack[8];
89836089Sjb					for (i = 0; i < datalen; ++i, ++cp) {
89936089Sjb						if ((i % 32) == 8)
90036089Sjb							(void)printf("\n\t");
90136089Sjb						(void)printf("%x ", *cp);
90236089Sjb					}
9031558Srgrimes					break;
9041558Srgrimes				}
9051558Srgrimes			}
9061558Srgrimes		}
9071558Srgrimes	} else {
90817724Sfenner		/*
90917724Sfenner		 * We've got something other than an ECHOREPLY.
91017724Sfenner		 * See if it's a reply to something that we sent.
91117724Sfenner		 * We can compare IP destination, protocol,
91217724Sfenner		 * and ICMP type and ID.
91323251Simp		 *
91423251Simp		 * Only print all the error messages if we are running
91523251Simp		 * as root to avoid leaking information not normally
91623251Simp		 * available to those not running as root.
91717724Sfenner		 */
91817724Sfenner#ifndef icmp_data
91917724Sfenner		struct ip *oip = &icp->icmp_ip;
92017724Sfenner#else
92117724Sfenner		struct ip *oip = (struct ip *)icp->icmp_data;
92217724Sfenner#endif
92317724Sfenner		struct icmp *oicmp = (struct icmp *)(oip + 1);
92417724Sfenner
92523295Simp		if (((options & F_VERBOSE) && uid == 0) ||
92617724Sfenner		    (!(options & F_QUIET2) &&
92779403Smjacob		     (oip->ip_dst.s_addr == whereto.sin_addr.s_addr) &&
92817724Sfenner		     (oip->ip_p == IPPROTO_ICMP) &&
92917724Sfenner		     (oicmp->icmp_type == ICMP_ECHO) &&
93017724Sfenner		     (oicmp->icmp_id == ident))) {
93117724Sfenner		    (void)printf("%d bytes from %s: ", cc,
93223247Swollman			pr_addr(from->sin_addr));
93317724Sfenner		    pr_icmph(icp);
93417724Sfenner		} else
93517724Sfenner		    return;
9361558Srgrimes	}
9371558Srgrimes
9381558Srgrimes	/* Display any IP options */
9391558Srgrimes	cp = (u_char *)buf + sizeof(struct ip);
9401558Srgrimes
9411558Srgrimes	for (; hlen > (int)sizeof(struct ip); --hlen, ++cp)
9421558Srgrimes		switch (*cp) {
9431558Srgrimes		case IPOPT_EOL:
9441558Srgrimes			hlen = 0;
9451558Srgrimes			break;
9461558Srgrimes		case IPOPT_LSRR:
9471558Srgrimes			(void)printf("\nLSRR: ");
9481558Srgrimes			hlen -= 2;
9491558Srgrimes			j = *++cp;
9501558Srgrimes			++cp;
9511558Srgrimes			if (j > IPOPT_MINOFF)
9521558Srgrimes				for (;;) {
9531558Srgrimes					l = *++cp;
9541558Srgrimes					l = (l<<8) + *++cp;
9551558Srgrimes					l = (l<<8) + *++cp;
9561558Srgrimes					l = (l<<8) + *++cp;
95723247Swollman					if (l == 0) {
95823247Swollman						printf("\t0.0.0.0");
95923247Swollman					} else {
96023247Swollman						struct in_addr ina;
96123247Swollman						ina.s_addr = ntohl(l);
96223247Swollman						printf("\t%s", pr_addr(ina));
96323247Swollman					}
9641558Srgrimes				hlen -= 4;
9651558Srgrimes				j -= 4;
9661558Srgrimes				if (j <= IPOPT_MINOFF)
9671558Srgrimes					break;
9681558Srgrimes				(void)putchar('\n');
9691558Srgrimes			}
9701558Srgrimes			break;
9711558Srgrimes		case IPOPT_RR:
9721558Srgrimes			j = *++cp;		/* get length */
9731558Srgrimes			i = *++cp;		/* and pointer */
9741558Srgrimes			hlen -= 2;
9751558Srgrimes			if (i > j)
9761558Srgrimes				i = j;
9771558Srgrimes			i -= IPOPT_MINOFF;
9781558Srgrimes			if (i <= 0)
9791558Srgrimes				continue;
9801558Srgrimes			if (i == old_rrlen
9811558Srgrimes			    && cp == (u_char *)buf + sizeof(struct ip) + 2
9821558Srgrimes			    && !bcmp((char *)cp, old_rr, i)
9831558Srgrimes			    && !(options & F_FLOOD)) {
9841558Srgrimes				(void)printf("\t(same route)");
9851558Srgrimes				i = ((i + 3) / 4) * 4;
9861558Srgrimes				hlen -= i;
9871558Srgrimes				cp += i;
9881558Srgrimes				break;
9891558Srgrimes			}
99034995Seivind			if (i < MAX_IPOPTLEN) {
99134976Simp				old_rrlen = i;
99234976Simp				bcopy((char *)cp, old_rr, i);
99334976Simp			} else
99434976Simp				old_rrlen = 0;
99534976Simp
9961558Srgrimes			(void)printf("\nRR: ");
99734976Simp			j = 0;
9981558Srgrimes			for (;;) {
9991558Srgrimes				l = *++cp;
10001558Srgrimes				l = (l<<8) + *++cp;
10011558Srgrimes				l = (l<<8) + *++cp;
10021558Srgrimes				l = (l<<8) + *++cp;
100323247Swollman				if (l == 0) {
100423247Swollman					printf("\t0.0.0.0");
100523247Swollman				} else {
100623247Swollman					struct in_addr ina;
100723247Swollman					ina.s_addr = ntohl(l);
100823247Swollman					printf("\t%s", pr_addr(ina));
100923247Swollman				}
10101558Srgrimes				hlen -= 4;
10111558Srgrimes				i -= 4;
101234976Simp				j += 4;
10131558Srgrimes				if (i <= 0)
10141558Srgrimes					break;
101534976Simp				if (j >= MAX_IPOPTLEN) {
101634976Simp					(void) printf("\t(truncated route)");
101734976Simp					break;
101834976Simp				}
10191558Srgrimes				(void)putchar('\n');
10201558Srgrimes			}
10211558Srgrimes			break;
10221558Srgrimes		case IPOPT_NOP:
10231558Srgrimes			(void)printf("\nNOP");
10241558Srgrimes			break;
10251558Srgrimes		default:
10261558Srgrimes			(void)printf("\nunknown option %x", *cp);
10271558Srgrimes			break;
10281558Srgrimes		}
10291558Srgrimes	if (!(options & F_FLOOD)) {
10301558Srgrimes		(void)putchar('\n');
10311558Srgrimes		(void)fflush(stdout);
10321558Srgrimes	}
10331558Srgrimes}
10341558Srgrimes
10351558Srgrimes/*
10361558Srgrimes * in_cksum --
10371558Srgrimes *	Checksum routine for Internet Protocol family headers (C Version)
10381558Srgrimes */
103923247Swollmanu_short
10401558Srgrimesin_cksum(addr, len)
10411558Srgrimes	u_short *addr;
10421558Srgrimes	int len;
10431558Srgrimes{
104493035Sobrien	int nleft, sum;
104593035Sobrien	u_short *w;
104653191Spb	union {
104753369Spb		u_short	us;
104853369Spb		u_char	uc[2];
104953369Spb	} last;
105053369Spb	u_short answer;
10511558Srgrimes
105293035Sobrien	nleft = len;
105393035Sobrien	sum = 0;
105493035Sobrien	w = addr;
105593035Sobrien
10561558Srgrimes	/*
10571558Srgrimes	 * Our algorithm is simple, using a 32 bit accumulator (sum), we add
10581558Srgrimes	 * sequential 16 bit words to it, and at the end, fold back all the
10591558Srgrimes	 * carry bits from the top 16 bits into the lower 16 bits.
10601558Srgrimes	 */
10611558Srgrimes	while (nleft > 1)  {
10621558Srgrimes		sum += *w++;
10631558Srgrimes		nleft -= 2;
10641558Srgrimes	}
10651558Srgrimes
10661558Srgrimes	/* mop up an odd byte, if necessary */
10671558Srgrimes	if (nleft == 1) {
106853369Spb		last.uc[0] = *(u_char *)w;
106953369Spb		last.uc[1] = 0;
107053369Spb		sum += last.us;
10711558Srgrimes	}
10721558Srgrimes
10731558Srgrimes	/* add back carry outs from top 16 bits to low 16 bits */
10741558Srgrimes	sum = (sum >> 16) + (sum & 0xffff);	/* add hi 16 to low 16 */
10751558Srgrimes	sum += (sum >> 16);			/* add carry */
107653369Spb	answer = ~sum;				/* truncate to 16 bits */
107753369Spb	return(answer);
10781558Srgrimes}
10791558Srgrimes
10801558Srgrimes/*
10811558Srgrimes * tvsub --
10821558Srgrimes *	Subtract 2 timeval structs:  out = out - in.  Out is assumed to
10831558Srgrimes * be >= in.
10841558Srgrimes */
108523247Swollmanstatic void
10861558Srgrimestvsub(out, in)
108792806Sobrien	struct timeval *out, *in;
10881558Srgrimes{
108993035Sobrien
10901558Srgrimes	if ((out->tv_usec -= in->tv_usec) < 0) {
10911558Srgrimes		--out->tv_sec;
10921558Srgrimes		out->tv_usec += 1000000;
10931558Srgrimes	}
10941558Srgrimes	out->tv_sec -= in->tv_sec;
10951558Srgrimes}
10961558Srgrimes
10971558Srgrimes/*
10983792Ssef * status --
10993792Ssef *	Print out statistics when SIGINFO is received.
11003792Ssef */
11013792Ssef
110223247Swollmanstatic void
110320280Sbdestatus(sig)
110420280Sbde	int sig;
110520280Sbde{
110693035Sobrien
110720195Ssef	siginfo_p = 1;
110820195Ssef}
110920195Ssef
111023247Swollmanstatic void
111120195Ssefcheck_status()
11123792Ssef{
111393035Sobrien
111420195Ssef	if (siginfo_p) {
111520195Ssef		siginfo_p = 0;
111620280Sbde		(void)fprintf(stderr,
111720280Sbde	"\r%ld/%ld packets received (%.0f%%) %.3f min / %.3f avg / %.3f max\n",
111820280Sbde		    nreceived, ntransmitted,
111920280Sbde		    ntransmitted ? nreceived * 100.0 / ntransmitted : 0.0,
112020280Sbde		    nreceived ? tmin : 0.0,
112120280Sbde		    nreceived + nrepeats ? tsum / (nreceived + nrepeats) : tsum,
112220280Sbde		    tmax);
112320195Ssef	}
11243792Ssef}
11253792Ssef
11263792Ssef/*
11271558Srgrimes * finish --
11281558Srgrimes *	Print out statistics, and give up.
11291558Srgrimes */
113023247Swollmanstatic void
113127533Sbdefinish()
11321558Srgrimes{
113393035Sobrien
11343792Ssef	struct termios ts;
11351558Srgrimes
11361558Srgrimes	(void)signal(SIGINT, SIG_IGN);
113727354Ssef	(void)signal(SIGALRM, SIG_IGN);
11381558Srgrimes	(void)putchar('\n');
11391558Srgrimes	(void)fflush(stdout);
11401558Srgrimes	(void)printf("--- %s ping statistics ---\n", hostname);
11411558Srgrimes	(void)printf("%ld packets transmitted, ", ntransmitted);
11421558Srgrimes	(void)printf("%ld packets received, ", nreceived);
11431558Srgrimes	if (nrepeats)
11441558Srgrimes		(void)printf("+%ld duplicates, ", nrepeats);
114546080Simp	if (ntransmitted) {
11461558Srgrimes		if (nreceived > ntransmitted)
11471558Srgrimes			(void)printf("-- somebody's printing up packets!");
11481558Srgrimes		else
11491558Srgrimes			(void)printf("%d%% packet loss",
11501558Srgrimes			    (int) (((ntransmitted - nreceived) * 100) /
11511558Srgrimes			    ntransmitted));
115246080Simp	}
11531558Srgrimes	(void)putchar('\n');
115427508Swollman	if (nreceived && timing) {
115527508Swollman		double n = nreceived + nrepeats;
115627508Swollman		double avg = tsum / n;
115727508Swollman		double vari = tsumsq / n - avg * avg;
115827508Swollman		printf("round-trip min/avg/max/stddev = "
115927508Swollman		       "%.3f/%.3f/%.3f/%.3f ms\n",
116027508Swollman		    tmin, avg, tmax, sqrt(vari));
116127508Swollman	}
116219395Sbde	if (reset_kerninfo && tcgetattr(STDOUT_FILENO, &ts) != -1) {
11633792Ssef		ts.c_lflag &= ~NOKERNINFO;
116419395Sbde		tcsetattr(STDOUT_FILENO, TCSANOW, &ts);
11653792Ssef	}
11663792Ssef
11678871Srgrimes	if (nreceived)
11684862Sdg		exit(0);
11694862Sdg	else
11704862Sdg		exit(2);
11711558Srgrimes}
11721558Srgrimes
11731558Srgrimes#ifdef notdef
11741558Srgrimesstatic char *ttab[] = {
11751558Srgrimes	"Echo Reply",		/* ip + seq + udata */
11761558Srgrimes	"Dest Unreachable",	/* net, host, proto, port, frag, sr + IP */
11771558Srgrimes	"Source Quench",	/* IP */
11781558Srgrimes	"Redirect",		/* redirect type, gateway, + IP  */
11791558Srgrimes	"Echo",
11801558Srgrimes	"Time Exceeded",	/* transit, frag reassem + IP */
11811558Srgrimes	"Parameter Problem",	/* pointer + IP */
11821558Srgrimes	"Timestamp",		/* id + seq + three timestamps */
11831558Srgrimes	"Timestamp Reply",	/* " */
11841558Srgrimes	"Info Request",		/* id + sq */
11851558Srgrimes	"Info Reply"		/* " */
11861558Srgrimes};
11871558Srgrimes#endif
11881558Srgrimes
11891558Srgrimes/*
11901558Srgrimes * pr_icmph --
11911558Srgrimes *	Print a descriptive string about an ICMP header.
11921558Srgrimes */
119323247Swollmanstatic void
11941558Srgrimespr_icmph(icp)
11951558Srgrimes	struct icmp *icp;
11961558Srgrimes{
119793035Sobrien
11981558Srgrimes	switch(icp->icmp_type) {
11991558Srgrimes	case ICMP_ECHOREPLY:
12001558Srgrimes		(void)printf("Echo Reply\n");
12011558Srgrimes		/* XXX ID + Seq + Data */
12021558Srgrimes		break;
12031558Srgrimes	case ICMP_UNREACH:
12041558Srgrimes		switch(icp->icmp_code) {
12051558Srgrimes		case ICMP_UNREACH_NET:
12061558Srgrimes			(void)printf("Destination Net Unreachable\n");
12071558Srgrimes			break;
12081558Srgrimes		case ICMP_UNREACH_HOST:
12091558Srgrimes			(void)printf("Destination Host Unreachable\n");
12101558Srgrimes			break;
12111558Srgrimes		case ICMP_UNREACH_PROTOCOL:
12121558Srgrimes			(void)printf("Destination Protocol Unreachable\n");
12131558Srgrimes			break;
12141558Srgrimes		case ICMP_UNREACH_PORT:
12151558Srgrimes			(void)printf("Destination Port Unreachable\n");
12161558Srgrimes			break;
12171558Srgrimes		case ICMP_UNREACH_NEEDFRAG:
121817724Sfenner			(void)printf("frag needed and DF set (MTU %d)\n",
121928059Sfenner					ntohs(icp->icmp_nextmtu));
12201558Srgrimes			break;
12211558Srgrimes		case ICMP_UNREACH_SRCFAIL:
12221558Srgrimes			(void)printf("Source Route Failed\n");
12231558Srgrimes			break;
122417724Sfenner		case ICMP_UNREACH_FILTER_PROHIB:
122517724Sfenner			(void)printf("Communication prohibited by filter\n");
122617724Sfenner			break;
12271558Srgrimes		default:
12281558Srgrimes			(void)printf("Dest Unreachable, Bad Code: %d\n",
12291558Srgrimes			    icp->icmp_code);
12301558Srgrimes			break;
12311558Srgrimes		}
12321558Srgrimes		/* Print returned IP header information */
12331558Srgrimes#ifndef icmp_data
12341558Srgrimes		pr_retip(&icp->icmp_ip);
12351558Srgrimes#else
12361558Srgrimes		pr_retip((struct ip *)icp->icmp_data);
12371558Srgrimes#endif
12381558Srgrimes		break;
12391558Srgrimes	case ICMP_SOURCEQUENCH:
12401558Srgrimes		(void)printf("Source Quench\n");
12411558Srgrimes#ifndef icmp_data
12421558Srgrimes		pr_retip(&icp->icmp_ip);
12431558Srgrimes#else
12441558Srgrimes		pr_retip((struct ip *)icp->icmp_data);
12451558Srgrimes#endif
12461558Srgrimes		break;
12471558Srgrimes	case ICMP_REDIRECT:
12481558Srgrimes		switch(icp->icmp_code) {
12491558Srgrimes		case ICMP_REDIRECT_NET:
12501558Srgrimes			(void)printf("Redirect Network");
12511558Srgrimes			break;
12521558Srgrimes		case ICMP_REDIRECT_HOST:
12531558Srgrimes			(void)printf("Redirect Host");
12541558Srgrimes			break;
12551558Srgrimes		case ICMP_REDIRECT_TOSNET:
12561558Srgrimes			(void)printf("Redirect Type of Service and Network");
12571558Srgrimes			break;
12581558Srgrimes		case ICMP_REDIRECT_TOSHOST:
12591558Srgrimes			(void)printf("Redirect Type of Service and Host");
12601558Srgrimes			break;
12611558Srgrimes		default:
12621558Srgrimes			(void)printf("Redirect, Bad Code: %d", icp->icmp_code);
12631558Srgrimes			break;
12641558Srgrimes		}
126528059Sfenner		(void)printf("(New addr: %s)\n", inet_ntoa(icp->icmp_gwaddr));
12661558Srgrimes#ifndef icmp_data
12671558Srgrimes		pr_retip(&icp->icmp_ip);
12681558Srgrimes#else
12691558Srgrimes		pr_retip((struct ip *)icp->icmp_data);
12701558Srgrimes#endif
12711558Srgrimes		break;
12721558Srgrimes	case ICMP_ECHO:
12731558Srgrimes		(void)printf("Echo Request\n");
12741558Srgrimes		/* XXX ID + Seq + Data */
12751558Srgrimes		break;
12761558Srgrimes	case ICMP_TIMXCEED:
12771558Srgrimes		switch(icp->icmp_code) {
12781558Srgrimes		case ICMP_TIMXCEED_INTRANS:
12791558Srgrimes			(void)printf("Time to live exceeded\n");
12801558Srgrimes			break;
12811558Srgrimes		case ICMP_TIMXCEED_REASS:
12821558Srgrimes			(void)printf("Frag reassembly time exceeded\n");
12831558Srgrimes			break;
12841558Srgrimes		default:
12851558Srgrimes			(void)printf("Time exceeded, Bad Code: %d\n",
12861558Srgrimes			    icp->icmp_code);
12871558Srgrimes			break;
12881558Srgrimes		}
12891558Srgrimes#ifndef icmp_data
12901558Srgrimes		pr_retip(&icp->icmp_ip);
12911558Srgrimes#else
12921558Srgrimes		pr_retip((struct ip *)icp->icmp_data);
12931558Srgrimes#endif
12941558Srgrimes		break;
12951558Srgrimes	case ICMP_PARAMPROB:
12961558Srgrimes		(void)printf("Parameter problem: pointer = 0x%02x\n",
12971558Srgrimes		    icp->icmp_hun.ih_pptr);
12981558Srgrimes#ifndef icmp_data
12991558Srgrimes		pr_retip(&icp->icmp_ip);
13001558Srgrimes#else
13011558Srgrimes		pr_retip((struct ip *)icp->icmp_data);
13021558Srgrimes#endif
13031558Srgrimes		break;
13041558Srgrimes	case ICMP_TSTAMP:
13051558Srgrimes		(void)printf("Timestamp\n");
13061558Srgrimes		/* XXX ID + Seq + 3 timestamps */
13071558Srgrimes		break;
13081558Srgrimes	case ICMP_TSTAMPREPLY:
13091558Srgrimes		(void)printf("Timestamp Reply\n");
13101558Srgrimes		/* XXX ID + Seq + 3 timestamps */
13111558Srgrimes		break;
13121558Srgrimes	case ICMP_IREQ:
13131558Srgrimes		(void)printf("Information Request\n");
13141558Srgrimes		/* XXX ID + Seq */
13151558Srgrimes		break;
13161558Srgrimes	case ICMP_IREQREPLY:
13171558Srgrimes		(void)printf("Information Reply\n");
13181558Srgrimes		/* XXX ID + Seq */
13191558Srgrimes		break;
13201558Srgrimes	case ICMP_MASKREQ:
13211558Srgrimes		(void)printf("Address Mask Request\n");
13221558Srgrimes		break;
13231558Srgrimes	case ICMP_MASKREPLY:
13241558Srgrimes		(void)printf("Address Mask Reply\n");
13251558Srgrimes		break;
132617724Sfenner	case ICMP_ROUTERADVERT:
132717724Sfenner		(void)printf("Router Advertisement\n");
132817724Sfenner		break;
132917724Sfenner	case ICMP_ROUTERSOLICIT:
133017724Sfenner		(void)printf("Router Solicitation\n");
133117724Sfenner		break;
13321558Srgrimes	default:
13331558Srgrimes		(void)printf("Bad ICMP type: %d\n", icp->icmp_type);
13341558Srgrimes	}
13351558Srgrimes}
13361558Srgrimes
13371558Srgrimes/*
13381558Srgrimes * pr_iph --
13391558Srgrimes *	Print an IP header with options.
13401558Srgrimes */
134123247Swollmanstatic void
13421558Srgrimespr_iph(ip)
13431558Srgrimes	struct ip *ip;
13441558Srgrimes{
134593035Sobrien	u_char *cp;
13461558Srgrimes	int hlen;
13471558Srgrimes
13481558Srgrimes	hlen = ip->ip_hl << 2;
13491558Srgrimes	cp = (u_char *)ip + 20;		/* point to options */
13501558Srgrimes
135117724Sfenner	(void)printf("Vr HL TOS  Len   ID Flg  off TTL Pro  cks      Src      Dst\n");
13521558Srgrimes	(void)printf(" %1x  %1x  %02x %04x %04x",
135317724Sfenner	    ip->ip_v, ip->ip_hl, ip->ip_tos, ntohs(ip->ip_len),
135417724Sfenner	    ntohs(ip->ip_id));
135536089Sjb	(void)printf("   %1lx %04lx",
135636089Sjb	    (u_long) (ntohl(ip->ip_off) & 0xe000) >> 13,
135736089Sjb	    (u_long) ntohl(ip->ip_off) & 0x1fff);
135817724Sfenner	(void)printf("  %02x  %02x %04x", ip->ip_ttl, ip->ip_p,
135917724Sfenner							    ntohs(ip->ip_sum));
13601558Srgrimes	(void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_src.s_addr));
13611558Srgrimes	(void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_dst.s_addr));
136217724Sfenner	/* dump any option bytes */
13631558Srgrimes	while (hlen-- > 20) {
13641558Srgrimes		(void)printf("%02x", *cp++);
13651558Srgrimes	}
13661558Srgrimes	(void)putchar('\n');
13671558Srgrimes}
13681558Srgrimes
13691558Srgrimes/*
13701558Srgrimes * pr_addr --
13711558Srgrimes *	Return an ascii host address as a dotted quad and optionally with
13721558Srgrimes * a hostname.
13731558Srgrimes */
137423247Swollmanstatic char *
137523247Swollmanpr_addr(ina)
137623247Swollman	struct in_addr ina;
13771558Srgrimes{
13781558Srgrimes	struct hostent *hp;
137923251Simp	static char buf[16 + 3 + MAXHOSTNAMELEN];
13801558Srgrimes
13811558Srgrimes	if ((options & F_NUMERIC) ||
138223247Swollman	    !(hp = gethostbyaddr((char *)&ina, 4, AF_INET)))
138323247Swollman		return inet_ntoa(ina);
13841558Srgrimes	else
138517320Speter		(void)snprintf(buf, sizeof(buf), "%s (%s)", hp->h_name,
138623247Swollman		    inet_ntoa(ina));
13871558Srgrimes	return(buf);
13881558Srgrimes}
13891558Srgrimes
13901558Srgrimes/*
13911558Srgrimes * pr_retip --
13921558Srgrimes *	Dump some info on a returned (via ICMP) IP packet.
13931558Srgrimes */
139423247Swollmanstatic void
13951558Srgrimespr_retip(ip)
13961558Srgrimes	struct ip *ip;
13971558Srgrimes{
139893035Sobrien	u_char *cp;
13991558Srgrimes	int hlen;
14001558Srgrimes
14011558Srgrimes	pr_iph(ip);
14021558Srgrimes	hlen = ip->ip_hl << 2;
14031558Srgrimes	cp = (u_char *)ip + hlen;
14041558Srgrimes
14051558Srgrimes	if (ip->ip_p == 6)
14061558Srgrimes		(void)printf("TCP: from port %u, to port %u (decimal)\n",
14071558Srgrimes		    (*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3)));
14081558Srgrimes	else if (ip->ip_p == 17)
14091558Srgrimes		(void)printf("UDP: from port %u, to port %u (decimal)\n",
14101558Srgrimes			(*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3)));
14111558Srgrimes}
14121558Srgrimes
141323247Swollmanstatic void
14141558Srgrimesfill(bp, patp)
14151558Srgrimes	char *bp, *patp;
14161558Srgrimes{
141793035Sobrien	char *cp;
141893035Sobrien	int pat[16];
141992806Sobrien	int ii, jj, kk;
14201558Srgrimes
142123247Swollman	for (cp = patp; *cp; cp++) {
142223247Swollman		if (!isxdigit(*cp))
142323247Swollman			errx(EX_USAGE,
142423247Swollman			     "patterns must be specified as hex digits");
142523247Swollman
142623247Swollman	}
14271558Srgrimes	ii = sscanf(patp,
14281558Srgrimes	    "%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x",
14291558Srgrimes	    &pat[0], &pat[1], &pat[2], &pat[3], &pat[4], &pat[5], &pat[6],
14301558Srgrimes	    &pat[7], &pat[8], &pat[9], &pat[10], &pat[11], &pat[12],
14311558Srgrimes	    &pat[13], &pat[14], &pat[15]);
14321558Srgrimes
14331558Srgrimes	if (ii > 0)
14341558Srgrimes		for (kk = 0;
143536089Sjb		    kk <= MAXPACKET - (8 + PHDR_LEN + ii);
14361558Srgrimes		    kk += ii)
14371558Srgrimes			for (jj = 0; jj < ii; ++jj)
14381558Srgrimes				bp[jj + kk] = pat[jj];
14391558Srgrimes	if (!(options & F_QUIET)) {
14401558Srgrimes		(void)printf("PATTERN: 0x");
14411558Srgrimes		for (jj = 0; jj < ii; ++jj)
14421558Srgrimes			(void)printf("%02x", bp[jj] & 0xFF);
14431558Srgrimes		(void)printf("\n");
14441558Srgrimes	}
14451558Srgrimes}
14461558Srgrimes
144723247Swollmanstatic void
144837671Scharnierusage()
14491558Srgrimes{
145042337Simp	fprintf(stderr, "%s\n%s\n%s\n",
145174029Sru"usage: ping [-QRadfnqrv] [-c count] [-i wait] [-l preload] [-m ttl]",
145274029Sru"            [-p pattern] "
145355505Sshin#ifdef IPSEC
145455505Sshin#ifdef IPSEC_POLICY_IPSEC
145555505Sshin"[-P policy] "
145655505Sshin#endif
145755505Sshin#endif
145855996Sbillf"[-s packetsize] [-S src_addr] [-t timeout]",
145955996Sbillf"            [host | [-L] [-I iface] [-T ttl] mcast-group]");
146023247Swollman	exit(EX_USAGE);
14611558Srgrimes}
1462