xref: /freebsd/sbin/ping/ping.c (revision c37420b0d5b3b6ef875fbf0b84a13f6f09be56d6)
1 /*
2  * Copyright (c) 1989, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Mike Muuss.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 4. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32 
33 #if 0
34 #ifndef lint
35 static const char copyright[] =
36 "@(#) Copyright (c) 1989, 1993\n\
37 	The Regents of the University of California.  All rights reserved.\n";
38 #endif /* not lint */
39 
40 #ifndef lint
41 static char sccsid[] = "@(#)ping.c	8.1 (Berkeley) 6/5/93";
42 #endif /* not lint */
43 #endif
44 #include <sys/cdefs.h>
45 __FBSDID("$FreeBSD$");
46 
47 /*
48  *			P I N G . C
49  *
50  * Using the Internet Control Message Protocol (ICMP) "ECHO" facility,
51  * measure round-trip-delays and packet loss across network paths.
52  *
53  * Author -
54  *	Mike Muuss
55  *	U. S. Army Ballistic Research Laboratory
56  *	December, 1983
57  *
58  * Status -
59  *	Public Domain.  Distribution Unlimited.
60  * Bugs -
61  *	More statistics could always be gathered.
62  *	This program has to run SUID to ROOT to access the ICMP socket.
63  */
64 
65 #include <sys/param.h>		/* NB: we rely on this for <sys/types.h> */
66 #include <sys/socket.h>
67 #include <sys/sysctl.h>
68 #include <sys/time.h>
69 #include <sys/uio.h>
70 
71 #include <netinet/in.h>
72 #include <netinet/in_systm.h>
73 #include <netinet/ip.h>
74 #include <netinet/ip_icmp.h>
75 #include <netinet/ip_var.h>
76 #include <arpa/inet.h>
77 
78 #ifdef IPSEC
79 #include <netinet6/ipsec.h>
80 #endif /*IPSEC*/
81 
82 #include <ctype.h>
83 #include <err.h>
84 #include <errno.h>
85 #include <math.h>
86 #include <netdb.h>
87 #include <signal.h>
88 #include <stdio.h>
89 #include <stdlib.h>
90 #include <string.h>
91 #include <sysexits.h>
92 #include <unistd.h>
93 
94 #define	INADDR_LEN	((int)sizeof(in_addr_t))
95 #define	TIMEVAL_LEN	((int)sizeof(struct timeval))
96 #define	MASK_LEN	(ICMP_MASKLEN - ICMP_MINLEN)
97 #define	TS_LEN		(ICMP_TSLEN - ICMP_MINLEN)
98 #define	DEFDATALEN	56		/* default data length */
99 #define	FLOOD_BACKOFF	20000		/* usecs to back off if F_FLOOD mode */
100 					/* runs out of buffer space */
101 #define	MAXIPLEN	(sizeof(struct ip) + MAX_IPOPTLEN)
102 #define	MAXICMPLEN	(ICMP_ADVLENMIN + MAX_IPOPTLEN)
103 #define	MAXWAIT		10		/* max seconds to wait for response */
104 #define	MAXALARM	(60 * 60)	/* max seconds for alarm timeout */
105 #define	MAXTOS		255
106 
107 #define	A(bit)		rcvd_tbl[(bit)>>3]	/* identify byte in array */
108 #define	B(bit)		(1 << ((bit) & 0x07))	/* identify bit in byte */
109 #define	SET(bit)	(A(bit) |= B(bit))
110 #define	CLR(bit)	(A(bit) &= (~B(bit)))
111 #define	TST(bit)	(A(bit) & B(bit))
112 
113 /* various options */
114 int options;
115 #define	F_FLOOD		0x0001
116 #define	F_INTERVAL	0x0002
117 #define	F_NUMERIC	0x0004
118 #define	F_PINGFILLED	0x0008
119 #define	F_QUIET		0x0010
120 #define	F_RROUTE	0x0020
121 #define	F_SO_DEBUG	0x0040
122 #define	F_SO_DONTROUTE	0x0080
123 #define	F_VERBOSE	0x0100
124 #define	F_QUIET2	0x0200
125 #define	F_NOLOOP	0x0400
126 #define	F_MTTL		0x0800
127 #define	F_MIF		0x1000
128 #define	F_AUDIBLE	0x2000
129 #ifdef IPSEC
130 #ifdef IPSEC_POLICY_IPSEC
131 #define F_POLICY	0x4000
132 #endif /*IPSEC_POLICY_IPSEC*/
133 #endif /*IPSEC*/
134 #define	F_TTL		0x8000
135 #define	F_MISSED	0x10000
136 #define	F_ONCE		0x20000
137 #define	F_HDRINCL	0x40000
138 #define	F_MASK		0x80000
139 #define	F_TIME		0x100000
140 
141 /*
142  * MAX_DUP_CHK is the number of bits in received table, i.e. the maximum
143  * number of received sequence numbers we can keep track of.  Change 128
144  * to 8192 for complete accuracy...
145  */
146 #define	MAX_DUP_CHK	(8 * 128)
147 int mx_dup_ck = MAX_DUP_CHK;
148 char rcvd_tbl[MAX_DUP_CHK / 8];
149 
150 struct sockaddr_in whereto;	/* who to ping */
151 int datalen = DEFDATALEN;
152 int maxpayload;
153 int s;				/* socket file descriptor */
154 u_char outpackhdr[IP_MAXPACKET], *outpack;
155 char BBELL = '\a';		/* characters written for MISSED and AUDIBLE */
156 char BSPACE = '\b';		/* characters written for flood */
157 char DOT = '.';
158 char *hostname;
159 char *shostname;
160 int ident;			/* process id to identify our packets */
161 int uid;			/* cached uid for micro-optimization */
162 u_char icmp_type = ICMP_ECHO;
163 u_char icmp_type_rsp = ICMP_ECHOREPLY;
164 int phdr_len = 0;
165 int send_len;
166 
167 /* counters */
168 long nmissedmax;		/* max value of ntransmitted - nreceived - 1 */
169 long npackets;			/* max packets to transmit */
170 long nreceived;			/* # of packets we got back */
171 long nrepeats;			/* number of duplicates */
172 long ntransmitted;		/* sequence # for outbound packets = #sent */
173 int interval = 1000;		/* interval between packets, ms */
174 
175 /* timing */
176 int timing;			/* flag to do timing */
177 double tmin = 999999999.0;	/* minimum round trip time */
178 double tmax = 0.0;		/* maximum round trip time */
179 double tsum = 0.0;		/* sum of all times, for doing average */
180 double tsumsq = 0.0;		/* sum of all times squared, for std. dev. */
181 
182 volatile sig_atomic_t finish_up;  /* nonzero if we've been told to finish up */
183 volatile sig_atomic_t siginfo_p;
184 
185 static void fill(char *, char *);
186 static u_short in_cksum(u_short *, int);
187 static void check_status(void);
188 static void finish(void) __dead2;
189 static void pinger(void);
190 static char *pr_addr(struct in_addr);
191 static char *pr_ntime(n_time);
192 static void pr_icmph(struct icmp *);
193 static void pr_iph(struct ip *);
194 static void pr_pack(char *, int, struct sockaddr_in *, struct timeval *);
195 static void pr_retip(struct ip *);
196 static void status(int);
197 static void stopit(int);
198 static void tvsub(struct timeval *, struct timeval *);
199 static void usage(void) __dead2;
200 
201 int
202 main(argc, argv)
203 	int argc;
204 	char *const *argv;
205 {
206 	struct sockaddr_in from, sock_in;
207 	struct in_addr ifaddr;
208 	struct timeval last, intvl;
209 	struct iovec iov;
210 	struct ip *ip;
211 	struct msghdr msg;
212 	struct sigaction si_sa;
213 	size_t sz;
214 	u_char *datap, packet[IP_MAXPACKET];
215 	char *ep, *source, *target, *payload;
216 	struct hostent *hp;
217 #ifdef IPSEC_POLICY_IPSEC
218 	char *policy_in, *policy_out;
219 #endif
220 	struct sockaddr_in *to;
221 	double t;
222 	u_long alarmtimeout, ultmp;
223 	int almost_done, ch, df, hold, i, icmp_len, mib[4], preload, sockerrno,
224 	    tos, ttl;
225 	char ctrl[CMSG_SPACE(sizeof(struct timeval))];
226 	char hnamebuf[MAXHOSTNAMELEN], snamebuf[MAXHOSTNAMELEN];
227 #ifdef IP_OPTIONS
228 	char rspace[MAX_IPOPTLEN];	/* record route space */
229 #endif
230 	unsigned char loop, mttl;
231 
232 	payload = source = NULL;
233 #ifdef IPSEC_POLICY_IPSEC
234 	policy_in = policy_out = NULL;
235 #endif
236 
237 	/*
238 	 * Do the stuff that we need root priv's for *first*, and
239 	 * then drop our setuid bit.  Save error reporting for
240 	 * after arg parsing.
241 	 */
242 	s = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
243 	sockerrno = errno;
244 
245 	setuid(getuid());
246 	uid = getuid();
247 
248 	alarmtimeout = df = preload = tos = 0;
249 
250 	outpack = outpackhdr + sizeof(struct ip);
251 	while ((ch = getopt(argc, argv,
252 		"Aac:DdfI:i:Ll:M:m:nop:QqRrS:s:T:t:vz:"
253 #ifdef IPSEC
254 #ifdef IPSEC_POLICY_IPSEC
255 		"P:"
256 #endif /*IPSEC_POLICY_IPSEC*/
257 #endif /*IPSEC*/
258 		)) != -1)
259 	{
260 		switch(ch) {
261 		case 'A':
262 			options |= F_MISSED;
263 			break;
264 		case 'a':
265 			options |= F_AUDIBLE;
266 			break;
267 		case 'c':
268 			ultmp = strtoul(optarg, &ep, 0);
269 			if (*ep || ep == optarg || ultmp > LONG_MAX || !ultmp)
270 				errx(EX_USAGE,
271 				    "invalid count of packets to transmit: `%s'",
272 				    optarg);
273 			npackets = ultmp;
274 			break;
275 		case 'D':
276 			options |= F_HDRINCL;
277 			df = 1;
278 			break;
279 		case 'd':
280 			options |= F_SO_DEBUG;
281 			break;
282 		case 'f':
283 			if (uid) {
284 				errno = EPERM;
285 				err(EX_NOPERM, "-f flag");
286 			}
287 			options |= F_FLOOD;
288 			setbuf(stdout, (char *)NULL);
289 			break;
290 		case 'I':		/* multicast interface */
291 			if (inet_aton(optarg, &ifaddr) == 0)
292 				errx(EX_USAGE,
293 				    "invalid multicast interface: `%s'",
294 				    optarg);
295 			options |= F_MIF;
296 			break;
297 		case 'i':		/* wait between sending packets */
298 			t = strtod(optarg, &ep) * 1000.0;
299 			if (*ep || ep == optarg || t > (double)INT_MAX)
300 				errx(EX_USAGE, "invalid timing interval: `%s'",
301 				    optarg);
302 			options |= F_INTERVAL;
303 			interval = (int)t;
304 			if (uid && interval < 1000) {
305 				errno = EPERM;
306 				err(EX_NOPERM, "-i interval too short");
307 			}
308 			break;
309 		case 'L':
310 			options |= F_NOLOOP;
311 			loop = 0;
312 			break;
313 		case 'l':
314 			ultmp = strtoul(optarg, &ep, 0);
315 			if (*ep || ep == optarg || ultmp > INT_MAX)
316 				errx(EX_USAGE,
317 				    "invalid preload value: `%s'", optarg);
318 			if (uid) {
319 				errno = EPERM;
320 				err(EX_NOPERM, "-l flag");
321 			}
322 			preload = ultmp;
323 			break;
324 		case 'M':
325 			switch(optarg[0]) {
326 			case 'M':
327 			case 'm':
328 				options |= F_MASK;
329 				break;
330 			case 'T':
331 			case 't':
332 				options |= F_TIME;
333 				break;
334 			default:
335 				errx(EX_USAGE, "invalid message: `%c'", optarg[0]);
336 				break;
337 			}
338 			break;
339 		case 'm':		/* TTL */
340 			ultmp = strtoul(optarg, &ep, 0);
341 			if (*ep || ep == optarg || ultmp > MAXTTL)
342 				errx(EX_USAGE, "invalid TTL: `%s'", optarg);
343 			ttl = ultmp;
344 			options |= F_TTL;
345 			break;
346 		case 'n':
347 			options |= F_NUMERIC;
348 			break;
349 		case 'o':
350 			options |= F_ONCE;
351 			break;
352 #ifdef IPSEC
353 #ifdef IPSEC_POLICY_IPSEC
354 		case 'P':
355 			options |= F_POLICY;
356 			if (!strncmp("in", optarg, 2))
357 				policy_in = strdup(optarg);
358 			else if (!strncmp("out", optarg, 3))
359 				policy_out = strdup(optarg);
360 			else
361 				errx(1, "invalid security policy");
362 			break;
363 #endif /*IPSEC_POLICY_IPSEC*/
364 #endif /*IPSEC*/
365 		case 'p':		/* fill buffer with user pattern */
366 			options |= F_PINGFILLED;
367 			payload = optarg;
368 			break;
369 		case 'Q':
370 			options |= F_QUIET2;
371 			break;
372 		case 'q':
373 			options |= F_QUIET;
374 			break;
375 		case 'R':
376 			options |= F_RROUTE;
377 			break;
378 		case 'r':
379 			options |= F_SO_DONTROUTE;
380 			break;
381 		case 'S':
382 			source = optarg;
383 			break;
384 		case 's':		/* size of packet to send */
385 			ultmp = strtoul(optarg, &ep, 0);
386 			if (*ep || ep == optarg)
387 				errx(EX_USAGE, "invalid packet size: `%s'",
388 				    optarg);
389 			if (uid != 0 && ultmp > DEFDATALEN) {
390 				errno = EPERM;
391 				err(EX_NOPERM,
392 				    "packet size too large: %lu > %u",
393 				    ultmp, DEFDATALEN);
394 			}
395 			datalen = ultmp;
396 			break;
397 		case 'T':		/* multicast TTL */
398 			ultmp = strtoul(optarg, &ep, 0);
399 			if (*ep || ep == optarg || ultmp > MAXTTL)
400 				errx(EX_USAGE, "invalid multicast TTL: `%s'",
401 				    optarg);
402 			mttl = ultmp;
403 			options |= F_MTTL;
404 			break;
405 		case 't':
406 			alarmtimeout = strtoul(optarg, &ep, 0);
407 			if ((alarmtimeout < 1) || (alarmtimeout == ULONG_MAX))
408 				errx(EX_USAGE, "invalid timeout: `%s'",
409 				    optarg);
410 			if (alarmtimeout > MAXALARM)
411 				errx(EX_USAGE, "invalid timeout: `%s' > %d",
412 				    optarg, MAXALARM);
413 			alarm((int)alarmtimeout);
414 			break;
415 		case 'v':
416 			options |= F_VERBOSE;
417 			break;
418 		case 'z':
419 			options |= F_HDRINCL;
420 			ultmp = strtoul(optarg, &ep, 0);
421 			if (*ep || ep == optarg || ultmp > MAXTOS)
422 				errx(EX_USAGE, "invalid TOS: `%s'", optarg);
423 			tos = ultmp;
424 			break;
425 		default:
426 			usage();
427 		}
428 	}
429 
430 	if (argc - optind != 1)
431 		usage();
432 	target = argv[optind];
433 
434 	switch (options & (F_MASK|F_TIME)) {
435 	case 0: break;
436 	case F_MASK:
437 		icmp_type = ICMP_MASKREQ;
438 		icmp_type_rsp = ICMP_MASKREPLY;
439 		phdr_len = MASK_LEN;
440 		if (!(options & F_QUIET))
441 			(void)printf("ICMP_MASKREQ\n");
442 		break;
443 	case F_TIME:
444 		icmp_type = ICMP_TSTAMP;
445 		icmp_type_rsp = ICMP_TSTAMPREPLY;
446 		phdr_len = TS_LEN;
447 		if (!(options & F_QUIET))
448 			(void)printf("ICMP_TSTAMP\n");
449 		break;
450 	default:
451 		errx(EX_USAGE, "ICMP_TSTAMP and ICMP_MASKREQ are exclusive.");
452 		break;
453 	}
454 	icmp_len = sizeof(struct ip) + ICMP_MINLEN + phdr_len;
455 	if (options & F_RROUTE)
456 		icmp_len += MAX_IPOPTLEN;
457 	maxpayload = IP_MAXPACKET - icmp_len;
458 	if (datalen > maxpayload)
459 		errx(EX_USAGE, "packet size too large: %d > %d", datalen,
460 		    maxpayload);
461 	send_len = icmp_len + datalen;
462 	datap = &outpack[ICMP_MINLEN + phdr_len + TIMEVAL_LEN];
463 	if (options & F_PINGFILLED) {
464 		fill((char *)datap, payload);
465 	}
466 	if (source) {
467 		bzero((char *)&sock_in, sizeof(sock_in));
468 		sock_in.sin_family = AF_INET;
469 		if (inet_aton(source, &sock_in.sin_addr) != 0) {
470 			shostname = source;
471 		} else {
472 			hp = gethostbyname2(source, AF_INET);
473 			if (!hp)
474 				errx(EX_NOHOST, "cannot resolve %s: %s",
475 				    source, hstrerror(h_errno));
476 
477 			sock_in.sin_len = sizeof sock_in;
478 			if ((unsigned)hp->h_length > sizeof(sock_in.sin_addr) ||
479 			    hp->h_length < 0)
480 				errx(1, "gethostbyname2: illegal address");
481 			memcpy(&sock_in.sin_addr, hp->h_addr_list[0],
482 			    sizeof(sock_in.sin_addr));
483 			(void)strncpy(snamebuf, hp->h_name,
484 			    sizeof(snamebuf) - 1);
485 			snamebuf[sizeof(snamebuf) - 1] = '\0';
486 			shostname = snamebuf;
487 		}
488 		if (bind(s, (struct sockaddr *)&sock_in, sizeof sock_in) == -1)
489 			err(1, "bind");
490 	}
491 
492 	bzero(&whereto, sizeof(whereto));
493 	to = &whereto;
494 	to->sin_family = AF_INET;
495 	to->sin_len = sizeof *to;
496 	if (inet_aton(target, &to->sin_addr) != 0) {
497 		hostname = target;
498 	} else {
499 		hp = gethostbyname2(target, AF_INET);
500 		if (!hp)
501 			errx(EX_NOHOST, "cannot resolve %s: %s",
502 			    target, hstrerror(h_errno));
503 
504 		if ((unsigned)hp->h_length > sizeof(to->sin_addr))
505 			errx(1, "gethostbyname2 returned an illegal address");
506 		memcpy(&to->sin_addr, hp->h_addr_list[0], sizeof to->sin_addr);
507 		(void)strncpy(hnamebuf, hp->h_name, sizeof(hnamebuf) - 1);
508 		hnamebuf[sizeof(hnamebuf) - 1] = '\0';
509 		hostname = hnamebuf;
510 	}
511 
512 	if (options & F_FLOOD && options & F_INTERVAL)
513 		errx(EX_USAGE, "-f and -i: incompatible options");
514 
515 	if (options & F_FLOOD && IN_MULTICAST(ntohl(to->sin_addr.s_addr)))
516 		errx(EX_USAGE,
517 		    "-f flag cannot be used with multicast destination");
518 	if (options & (F_MIF | F_NOLOOP | F_MTTL)
519 	    && !IN_MULTICAST(ntohl(to->sin_addr.s_addr)))
520 		errx(EX_USAGE,
521 		    "-I, -L, -T flags cannot be used with unicast destination");
522 
523 	if (datalen >= TIMEVAL_LEN)	/* can we time transfer */
524 		timing = 1;
525 
526 	if (!(options & F_PINGFILLED))
527 		for (i = TIMEVAL_LEN; i < datalen; ++i)
528 			*datap++ = i;
529 
530 	ident = getpid() & 0xFFFF;
531 
532 	if (s < 0) {
533 		errno = sockerrno;
534 		err(EX_OSERR, "socket");
535 	}
536 	hold = 1;
537 	if (options & F_SO_DEBUG)
538 		(void)setsockopt(s, SOL_SOCKET, SO_DEBUG, (char *)&hold,
539 		    sizeof(hold));
540 	if (options & F_SO_DONTROUTE)
541 		(void)setsockopt(s, SOL_SOCKET, SO_DONTROUTE, (char *)&hold,
542 		    sizeof(hold));
543 #ifdef IPSEC
544 #ifdef IPSEC_POLICY_IPSEC
545 	if (options & F_POLICY) {
546 		char *buf;
547 		if (policy_in != NULL) {
548 			buf = ipsec_set_policy(policy_in, strlen(policy_in));
549 			if (buf == NULL)
550 				errx(EX_CONFIG, "%s", ipsec_strerror());
551 			if (setsockopt(s, IPPROTO_IP, IP_IPSEC_POLICY,
552 					buf, ipsec_get_policylen(buf)) < 0)
553 				err(EX_CONFIG,
554 				    "ipsec policy cannot be configured");
555 			free(buf);
556 		}
557 
558 		if (policy_out != NULL) {
559 			buf = ipsec_set_policy(policy_out, strlen(policy_out));
560 			if (buf == NULL)
561 				errx(EX_CONFIG, "%s", ipsec_strerror());
562 			if (setsockopt(s, IPPROTO_IP, IP_IPSEC_POLICY,
563 					buf, ipsec_get_policylen(buf)) < 0)
564 				err(EX_CONFIG,
565 				    "ipsec policy cannot be configured");
566 			free(buf);
567 		}
568 	}
569 #endif /*IPSEC_POLICY_IPSEC*/
570 #endif /*IPSEC*/
571 
572 	if (options & F_HDRINCL) {
573 		ip = (struct ip*)outpackhdr;
574 		if (!(options & (F_TTL | F_MTTL))) {
575 			mib[0] = CTL_NET;
576 			mib[1] = PF_INET;
577 			mib[2] = IPPROTO_IP;
578 			mib[3] = IPCTL_DEFTTL;
579 			sz = sizeof(ttl);
580 			if (sysctl(mib, 4, &ttl, &sz, NULL, 0) == -1)
581 				err(1, "sysctl(net.inet.ip.ttl)");
582 		}
583 		setsockopt(s, IPPROTO_IP, IP_HDRINCL, &hold, sizeof(hold));
584 		ip->ip_v = IPVERSION;
585 		ip->ip_hl = sizeof(struct ip) >> 2;
586 		ip->ip_tos = tos;
587 		ip->ip_id = 0;
588 		ip->ip_off = df ? IP_DF : 0;
589 		ip->ip_ttl = ttl;
590 		ip->ip_p = IPPROTO_ICMP;
591 		ip->ip_src.s_addr = source ? sock_in.sin_addr.s_addr : INADDR_ANY;
592 		ip->ip_dst = to->sin_addr;
593         }
594 	/* record route option */
595 	if (options & F_RROUTE) {
596 #ifdef IP_OPTIONS
597 		bzero(rspace, sizeof(rspace));
598 		rspace[IPOPT_OPTVAL] = IPOPT_RR;
599 		rspace[IPOPT_OLEN] = sizeof(rspace) - 1;
600 		rspace[IPOPT_OFFSET] = IPOPT_MINOFF;
601 		rspace[sizeof(rspace) - 1] = IPOPT_EOL;
602 		if (setsockopt(s, IPPROTO_IP, IP_OPTIONS, rspace,
603 		    sizeof(rspace)) < 0)
604 			err(EX_OSERR, "setsockopt IP_OPTIONS");
605 #else
606 		errx(EX_UNAVAILABLE,
607 		    "record route not available in this implementation");
608 #endif /* IP_OPTIONS */
609 	}
610 
611 	if (options & F_TTL) {
612 		if (setsockopt(s, IPPROTO_IP, IP_TTL, &ttl,
613 		    sizeof(ttl)) < 0) {
614 			err(EX_OSERR, "setsockopt IP_TTL");
615 		}
616 	}
617 	if (options & F_NOLOOP) {
618 		if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_LOOP, &loop,
619 		    sizeof(loop)) < 0) {
620 			err(EX_OSERR, "setsockopt IP_MULTICAST_LOOP");
621 		}
622 	}
623 	if (options & F_MTTL) {
624 		if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL, &mttl,
625 		    sizeof(mttl)) < 0) {
626 			err(EX_OSERR, "setsockopt IP_MULTICAST_TTL");
627 		}
628 	}
629 	if (options & F_MIF) {
630 		if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_IF, &ifaddr,
631 		    sizeof(ifaddr)) < 0) {
632 			err(EX_OSERR, "setsockopt IP_MULTICAST_IF");
633 		}
634 	}
635 #ifdef SO_TIMESTAMP
636 	{ int on = 1;
637 	if (setsockopt(s, SOL_SOCKET, SO_TIMESTAMP, &on, sizeof(on)) < 0)
638 		err(EX_OSERR, "setsockopt SO_TIMESTAMP");
639 	}
640 #endif
641 
642 	/*
643 	 * When pinging the broadcast address, you can get a lot of answers.
644 	 * Doing something so evil is useful if you are trying to stress the
645 	 * ethernet, or just want to fill the arp cache to get some stuff for
646 	 * /etc/ethers.  But beware: RFC 1122 allows hosts to ignore broadcast
647 	 * or multicast pings if they wish.
648 	 */
649 
650 	/*
651 	 * XXX receive buffer needs undetermined space for mbuf overhead
652 	 * as well.
653 	 */
654 	hold = IP_MAXPACKET + 128;
655 	(void)setsockopt(s, SOL_SOCKET, SO_RCVBUF, (char *)&hold,
656 	    sizeof(hold));
657 	if (uid == 0)
658 		(void)setsockopt(s, SOL_SOCKET, SO_SNDBUF, (char *)&hold,
659 		    sizeof(hold));
660 
661 	if (to->sin_family == AF_INET) {
662 		(void)printf("PING %s (%s)", hostname,
663 		    inet_ntoa(to->sin_addr));
664 		if (source)
665 			(void)printf(" from %s", shostname);
666 		(void)printf(": %d data bytes\n", datalen);
667 	} else
668 		(void)printf("PING %s: %d data bytes\n", hostname, datalen);
669 
670 	/*
671 	 * Use sigaction() instead of signal() to get unambiguous semantics,
672 	 * in particular with SA_RESTART not set.
673 	 */
674 
675 	sigemptyset(&si_sa.sa_mask);
676 	si_sa.sa_flags = 0;
677 
678 	si_sa.sa_handler = stopit;
679 	if (sigaction(SIGINT, &si_sa, 0) == -1) {
680 		err(EX_OSERR, "sigaction SIGINT");
681 	}
682 
683 	si_sa.sa_handler = status;
684 	if (sigaction(SIGINFO, &si_sa, 0) == -1) {
685 		err(EX_OSERR, "sigaction");
686 	}
687 
688         if (alarmtimeout > 0) {
689 		si_sa.sa_handler = stopit;
690 		if (sigaction(SIGALRM, &si_sa, 0) == -1)
691 			err(EX_OSERR, "sigaction SIGALRM");
692         }
693 
694 	bzero(&msg, sizeof(msg));
695 	msg.msg_name = (caddr_t)&from;
696 	msg.msg_iov = &iov;
697 	msg.msg_iovlen = 1;
698 #ifdef SO_TIMESTAMP
699 	msg.msg_control = (caddr_t)ctrl;
700 #endif
701 	iov.iov_base = packet;
702 	iov.iov_len = IP_MAXPACKET;
703 
704 	if (preload == 0)
705 		pinger();		/* send the first ping */
706 	else {
707 		if (npackets != 0 && preload > npackets)
708 			preload = npackets;
709 		while (preload--)	/* fire off them quickies */
710 			pinger();
711 	}
712 	(void)gettimeofday(&last, NULL);
713 
714 	if (options & F_FLOOD) {
715 		intvl.tv_sec = 0;
716 		intvl.tv_usec = 10000;
717 	} else {
718 		intvl.tv_sec = interval / 1000;
719 		intvl.tv_usec = interval % 1000 * 1000;
720 	}
721 
722 	almost_done = 0;
723 	while (!finish_up) {
724 		struct timeval now, timeout;
725 		fd_set rfds;
726 		int cc, n;
727 
728 		check_status();
729 		if ((unsigned)s >= FD_SETSIZE)
730 			errx(EX_OSERR, "descriptor too large");
731 		FD_ZERO(&rfds);
732 		FD_SET(s, &rfds);
733 		(void)gettimeofday(&now, NULL);
734 		timeout.tv_sec = last.tv_sec + intvl.tv_sec - now.tv_sec;
735 		timeout.tv_usec = last.tv_usec + intvl.tv_usec - now.tv_usec;
736 		while (timeout.tv_usec < 0) {
737 			timeout.tv_usec += 1000000;
738 			timeout.tv_sec--;
739 		}
740 		while (timeout.tv_usec >= 1000000) {
741 			timeout.tv_usec -= 1000000;
742 			timeout.tv_sec++;
743 		}
744 		if (timeout.tv_sec < 0)
745 			timeout.tv_sec = timeout.tv_usec = 0;
746 		n = select(s + 1, &rfds, NULL, NULL, &timeout);
747 		if (n < 0)
748 			continue;	/* Must be EINTR. */
749 		if (n == 1) {
750 			struct timeval *tv = NULL;
751 #ifdef SO_TIMESTAMP
752 			struct cmsghdr *cmsg = (struct cmsghdr *)&ctrl;
753 
754 			msg.msg_controllen = sizeof(ctrl);
755 #endif
756 			msg.msg_namelen = sizeof(from);
757 			if ((cc = recvmsg(s, &msg, 0)) < 0) {
758 				if (errno == EINTR)
759 					continue;
760 				warn("recvmsg");
761 				continue;
762 			}
763 #ifdef SO_TIMESTAMP
764 			if (cmsg->cmsg_level == SOL_SOCKET &&
765 			    cmsg->cmsg_type == SCM_TIMESTAMP &&
766 			    cmsg->cmsg_len == CMSG_LEN(sizeof *tv)) {
767 				/* Copy to avoid alignment problems: */
768 				memcpy(&now, CMSG_DATA(cmsg), sizeof(now));
769 				tv = &now;
770 			}
771 #endif
772 			if (tv == NULL) {
773 				(void)gettimeofday(&now, NULL);
774 				tv = &now;
775 			}
776 			pr_pack((char *)packet, cc, &from, tv);
777 			if ((options & F_ONCE && nreceived) ||
778 			    (npackets && nreceived >= npackets))
779 				break;
780 		}
781 		if (n == 0 || options & F_FLOOD) {
782 			if (!npackets || ntransmitted < npackets)
783 				pinger();
784 			else {
785 				if (almost_done)
786 					break;
787 				almost_done = 1;
788 				intvl.tv_usec = 0;
789 				if (nreceived) {
790 					intvl.tv_sec = 2 * tmax / 1000;
791 					if (!intvl.tv_sec)
792 						intvl.tv_sec = 1;
793 				} else
794 					intvl.tv_sec = MAXWAIT;
795 			}
796 			(void)gettimeofday(&last, NULL);
797 			if (ntransmitted - nreceived - 1 > nmissedmax) {
798 				nmissedmax = ntransmitted - nreceived - 1;
799 				if (options & F_MISSED)
800 					(void)write(STDOUT_FILENO, &BBELL, 1);
801 			}
802 		}
803 	}
804 	finish();
805 	/* NOTREACHED */
806 	exit(0);	/* Make the compiler happy */
807 }
808 
809 /*
810  * stopit --
811  *	Set the global bit that causes the main loop to quit.
812  * Do NOT call finish() from here, since finish() does far too much
813  * to be called from a signal handler.
814  */
815 void
816 stopit(sig)
817 	int sig __unused;
818 {
819 
820 	/*
821 	 * When doing reverse DNS lookups, the finish_up flag might not
822 	 * be noticed for a while.  Just exit if we get a second SIGINT.
823 	 */
824 	if (!(options & F_NUMERIC) && finish_up)
825 		_exit(nreceived ? 0 : 2);
826 	finish_up = 1;
827 }
828 
829 /*
830  * pinger --
831  *	Compose and transmit an ICMP ECHO REQUEST packet.  The IP packet
832  * will be added on by the kernel.  The ID field is our UNIX process ID,
833  * and the sequence number is an ascending integer.  The first TIMEVAL_LEN
834  * bytes of the data portion are used to hold a UNIX "timeval" struct in
835  * host byte-order, to compute the round-trip time.
836  */
837 static void
838 pinger(void)
839 {
840 	struct timeval now;
841 	struct ip *ip;
842 	struct icmp *icp;
843 	int cc, i;
844 	u_char *packet;
845 
846 	packet = outpack;
847 	icp = (struct icmp *)outpack;
848 	icp->icmp_type = icmp_type;
849 	icp->icmp_code = 0;
850 	icp->icmp_cksum = 0;
851 	icp->icmp_seq = htons(ntransmitted);
852 	icp->icmp_id = ident;			/* ID */
853 
854 	CLR(ntransmitted % mx_dup_ck);
855 
856 	if ((options & F_TIME) || timing) {
857 		(void)gettimeofday(&now, NULL);
858 
859 		if (options & F_TIME)
860 			icp->icmp_otime = htonl((now.tv_sec % (24*60*60))
861 				* 1000 + now.tv_usec / 1000);
862 		if (timing)
863 			bcopy((void *)&now,
864 			    (void *)&outpack[ICMP_MINLEN + phdr_len],
865 			    sizeof(struct timeval));
866 	}
867 
868 	cc = ICMP_MINLEN + phdr_len + datalen;
869 
870 	/* compute ICMP checksum here */
871 	icp->icmp_cksum = in_cksum((u_short *)icp, cc);
872 
873 	if (options & F_HDRINCL) {
874 		cc += sizeof(struct ip);
875 		ip = (struct ip *)outpackhdr;
876 		ip->ip_len = cc;
877 		ip->ip_sum = in_cksum((u_short *)outpackhdr, cc);
878 		packet = outpackhdr;
879 	}
880 	i = sendto(s, (char *)packet, cc, 0, (struct sockaddr *)&whereto,
881 	    sizeof(whereto));
882 
883 	if (i < 0 || i != cc)  {
884 		if (i < 0) {
885 			if (options & F_FLOOD && errno == ENOBUFS) {
886 				usleep(FLOOD_BACKOFF);
887 				return;
888 			}
889 			warn("sendto");
890 		} else {
891 			warn("%s: partial write: %d of %d bytes",
892 			     hostname, i, cc);
893 		}
894 	}
895 	ntransmitted++;
896 	if (!(options & F_QUIET) && options & F_FLOOD)
897 		(void)write(STDOUT_FILENO, &DOT, 1);
898 }
899 
900 /*
901  * pr_pack --
902  *	Print out the packet, if it came from us.  This logic is necessary
903  * because ALL readers of the ICMP socket get a copy of ALL ICMP packets
904  * which arrive ('tis only fair).  This permits multiple copies of this
905  * program to be run without having intermingled output (or statistics!).
906  */
907 static void
908 pr_pack(buf, cc, from, tv)
909 	char *buf;
910 	int cc;
911 	struct sockaddr_in *from;
912 	struct timeval *tv;
913 {
914 	struct in_addr ina;
915 	u_char *cp, *dp;
916 	struct icmp *icp;
917 	struct ip *ip;
918 	const void *tp;
919 	double triptime;
920 	int dupflag, hlen, i, j, recv_len, seq;
921 	static int old_rrlen;
922 	static char old_rr[MAX_IPOPTLEN];
923 
924 	/* Check the IP header */
925 	ip = (struct ip *)buf;
926 	hlen = ip->ip_hl << 2;
927 	recv_len = cc;
928 	if (cc < hlen + ICMP_MINLEN) {
929 		if (options & F_VERBOSE)
930 			warn("packet too short (%d bytes) from %s", cc,
931 			     inet_ntoa(from->sin_addr));
932 		return;
933 	}
934 
935 	/* Now the ICMP part */
936 	cc -= hlen;
937 	icp = (struct icmp *)(buf + hlen);
938 	if (icp->icmp_type == icmp_type_rsp) {
939 		if (icp->icmp_id != ident)
940 			return;			/* 'Twas not our ECHO */
941 		++nreceived;
942 		triptime = 0.0;
943 		if (timing) {
944 			struct timeval tv1;
945 #ifndef icmp_data
946 			tp = &icp->icmp_ip;
947 #else
948 			tp = icp->icmp_data;
949 #endif
950 			tp = (const char *)tp + phdr_len;
951 
952 			if (cc - ICMP_MINLEN - phdr_len >= sizeof(tv1)) {
953 				/* Copy to avoid alignment problems: */
954 				memcpy(&tv1, tp, sizeof(tv1));
955 				tvsub(tv, &tv1);
956  				triptime = ((double)tv->tv_sec) * 1000.0 +
957  				    ((double)tv->tv_usec) / 1000.0;
958 				tsum += triptime;
959 				tsumsq += triptime * triptime;
960 				if (triptime < tmin)
961 					tmin = triptime;
962 				if (triptime > tmax)
963 					tmax = triptime;
964 			} else
965 				timing = 0;
966 		}
967 
968 		seq = ntohs(icp->icmp_seq);
969 
970 		if (TST(seq % mx_dup_ck)) {
971 			++nrepeats;
972 			--nreceived;
973 			dupflag = 1;
974 		} else {
975 			SET(seq % mx_dup_ck);
976 			dupflag = 0;
977 		}
978 
979 		if (options & F_QUIET)
980 			return;
981 
982 		if (options & F_FLOOD)
983 			(void)write(STDOUT_FILENO, &BSPACE, 1);
984 		else {
985 			(void)printf("%d bytes from %s: icmp_seq=%u", cc,
986 			   inet_ntoa(*(struct in_addr *)&from->sin_addr.s_addr),
987 			   seq);
988 			(void)printf(" ttl=%d", ip->ip_ttl);
989 			if (timing)
990 				(void)printf(" time=%.3f ms", triptime);
991 			if (dupflag)
992 				(void)printf(" (DUP!)");
993 			if (options & F_AUDIBLE)
994 				(void)write(STDOUT_FILENO, &BBELL, 1);
995 			if (options & F_MASK) {
996 				/* Just prentend this cast isn't ugly */
997 				(void)printf(" mask=%s",
998 					pr_addr(*(struct in_addr *)&(icp->icmp_mask)));
999 			}
1000 			if (options & F_TIME) {
1001 				(void)printf(" tso=%s", pr_ntime(icp->icmp_otime));
1002 				(void)printf(" tsr=%s", pr_ntime(icp->icmp_rtime));
1003 				(void)printf(" tst=%s", pr_ntime(icp->icmp_ttime));
1004 			}
1005 			if (recv_len != send_len) {
1006                         	(void)printf(
1007 				     "\nwrong total length %d instead of %d",
1008 				     recv_len, send_len);
1009 			}
1010 			/* check the data */
1011 			cp = (u_char*)&icp->icmp_data[phdr_len];
1012 			dp = &outpack[ICMP_MINLEN + phdr_len];
1013 			cc -= ICMP_MINLEN + phdr_len;
1014 			i = 0;
1015 			if (timing) {   /* don't check variable timestamp */
1016 				cp += TIMEVAL_LEN;
1017 				dp += TIMEVAL_LEN;
1018 				cc -= TIMEVAL_LEN;
1019 				i += TIMEVAL_LEN;
1020 			}
1021 			for (; i < datalen && cc > 0; ++i, ++cp, ++dp, --cc) {
1022 				if (*cp != *dp) {
1023 	(void)printf("\nwrong data byte #%d should be 0x%x but was 0x%x",
1024 	    i, *dp, *cp);
1025 					(void)printf("\ncp:");
1026 					cp = (u_char*)&icp->icmp_data[0];
1027 					for (i = 0; i < datalen; ++i, ++cp) {
1028 						if ((i % 16) == 8)
1029 							(void)printf("\n\t");
1030 						(void)printf("%2x ", *cp);
1031 					}
1032 					(void)printf("\ndp:");
1033 					cp = &outpack[ICMP_MINLEN];
1034 					for (i = 0; i < datalen; ++i, ++cp) {
1035 						if ((i % 16) == 8)
1036 							(void)printf("\n\t");
1037 						(void)printf("%2x ", *cp);
1038 					}
1039 					break;
1040 				}
1041 			}
1042 		}
1043 	} else {
1044 		/*
1045 		 * We've got something other than an ECHOREPLY.
1046 		 * See if it's a reply to something that we sent.
1047 		 * We can compare IP destination, protocol,
1048 		 * and ICMP type and ID.
1049 		 *
1050 		 * Only print all the error messages if we are running
1051 		 * as root to avoid leaking information not normally
1052 		 * available to those not running as root.
1053 		 */
1054 #ifndef icmp_data
1055 		struct ip *oip = &icp->icmp_ip;
1056 #else
1057 		struct ip *oip = (struct ip *)icp->icmp_data;
1058 #endif
1059 		struct icmp *oicmp = (struct icmp *)(oip + 1);
1060 
1061 		if (((options & F_VERBOSE) && uid == 0) ||
1062 		    (!(options & F_QUIET2) &&
1063 		     (oip->ip_dst.s_addr == whereto.sin_addr.s_addr) &&
1064 		     (oip->ip_p == IPPROTO_ICMP) &&
1065 		     (oicmp->icmp_type == ICMP_ECHO) &&
1066 		     (oicmp->icmp_id == ident))) {
1067 		    (void)printf("%d bytes from %s: ", cc,
1068 			pr_addr(from->sin_addr));
1069 		    pr_icmph(icp);
1070 		} else
1071 		    return;
1072 	}
1073 
1074 	/* Display any IP options */
1075 	cp = (u_char *)buf + sizeof(struct ip);
1076 
1077 	for (; hlen > (int)sizeof(struct ip); --hlen, ++cp)
1078 		switch (*cp) {
1079 		case IPOPT_EOL:
1080 			hlen = 0;
1081 			break;
1082 		case IPOPT_LSRR:
1083 		case IPOPT_SSRR:
1084 			(void)printf(*cp == IPOPT_LSRR ?
1085 			    "\nLSRR: " : "\nSSRR: ");
1086 			j = cp[IPOPT_OLEN] - IPOPT_MINOFF + 1;
1087 			hlen -= 2;
1088 			cp += 2;
1089 			if (j >= INADDR_LEN &&
1090 			    j <= hlen - (int)sizeof(struct ip)) {
1091 				for (;;) {
1092 					bcopy(++cp, &ina.s_addr, INADDR_LEN);
1093 					if (ina.s_addr == 0)
1094 						(void)printf("\t0.0.0.0");
1095 					else
1096 						(void)printf("\t%s",
1097 						     pr_addr(ina));
1098 					hlen -= INADDR_LEN;
1099 					cp += INADDR_LEN - 1;
1100 					j -= INADDR_LEN;
1101 					if (j < INADDR_LEN)
1102 						break;
1103 					(void)putchar('\n');
1104 				}
1105 			} else
1106 				(void)printf("\t(truncated route)\n");
1107 			break;
1108 		case IPOPT_RR:
1109 			j = cp[IPOPT_OLEN];		/* get length */
1110 			i = cp[IPOPT_OFFSET];		/* and pointer */
1111 			hlen -= 2;
1112 			cp += 2;
1113 			if (i > j)
1114 				i = j;
1115 			i = i - IPOPT_MINOFF + 1;
1116 			if (i < 0 || i > (hlen - (int)sizeof(struct ip))) {
1117 				old_rrlen = 0;
1118 				continue;
1119 			}
1120 			if (i == old_rrlen
1121 			    && !bcmp((char *)cp, old_rr, i)
1122 			    && !(options & F_FLOOD)) {
1123 				(void)printf("\t(same route)");
1124 				hlen -= i;
1125 				cp += i;
1126 				break;
1127 			}
1128 			old_rrlen = i;
1129 			bcopy((char *)cp, old_rr, i);
1130 			(void)printf("\nRR: ");
1131 			if (i >= INADDR_LEN &&
1132 			    i <= hlen - (int)sizeof(struct ip)) {
1133 				for (;;) {
1134 					bcopy(++cp, &ina.s_addr, INADDR_LEN);
1135 					if (ina.s_addr == 0)
1136 						(void)printf("\t0.0.0.0");
1137 					else
1138 						(void)printf("\t%s",
1139 						     pr_addr(ina));
1140 					hlen -= INADDR_LEN;
1141 					cp += INADDR_LEN - 1;
1142 					i -= INADDR_LEN;
1143 					if (i < INADDR_LEN)
1144 						break;
1145 					(void)putchar('\n');
1146 				}
1147 			} else
1148 				(void)printf("\t(truncated route)");
1149 			break;
1150 		case IPOPT_NOP:
1151 			(void)printf("\nNOP");
1152 			break;
1153 		default:
1154 			(void)printf("\nunknown option %x", *cp);
1155 			break;
1156 		}
1157 	if (!(options & F_FLOOD)) {
1158 		(void)putchar('\n');
1159 		(void)fflush(stdout);
1160 	}
1161 }
1162 
1163 /*
1164  * in_cksum --
1165  *	Checksum routine for Internet Protocol family headers (C Version)
1166  */
1167 u_short
1168 in_cksum(addr, len)
1169 	u_short *addr;
1170 	int len;
1171 {
1172 	int nleft, sum;
1173 	u_short *w;
1174 	union {
1175 		u_short	us;
1176 		u_char	uc[2];
1177 	} last;
1178 	u_short answer;
1179 
1180 	nleft = len;
1181 	sum = 0;
1182 	w = addr;
1183 
1184 	/*
1185 	 * Our algorithm is simple, using a 32 bit accumulator (sum), we add
1186 	 * sequential 16 bit words to it, and at the end, fold back all the
1187 	 * carry bits from the top 16 bits into the lower 16 bits.
1188 	 */
1189 	while (nleft > 1)  {
1190 		sum += *w++;
1191 		nleft -= 2;
1192 	}
1193 
1194 	/* mop up an odd byte, if necessary */
1195 	if (nleft == 1) {
1196 		last.uc[0] = *(u_char *)w;
1197 		last.uc[1] = 0;
1198 		sum += last.us;
1199 	}
1200 
1201 	/* add back carry outs from top 16 bits to low 16 bits */
1202 	sum = (sum >> 16) + (sum & 0xffff);	/* add hi 16 to low 16 */
1203 	sum += (sum >> 16);			/* add carry */
1204 	answer = ~sum;				/* truncate to 16 bits */
1205 	return(answer);
1206 }
1207 
1208 /*
1209  * tvsub --
1210  *	Subtract 2 timeval structs:  out = out - in.  Out is assumed to
1211  * be >= in.
1212  */
1213 static void
1214 tvsub(out, in)
1215 	struct timeval *out, *in;
1216 {
1217 
1218 	if ((out->tv_usec -= in->tv_usec) < 0) {
1219 		--out->tv_sec;
1220 		out->tv_usec += 1000000;
1221 	}
1222 	out->tv_sec -= in->tv_sec;
1223 }
1224 
1225 /*
1226  * status --
1227  *	Print out statistics when SIGINFO is received.
1228  */
1229 
1230 static void
1231 status(sig)
1232 	int sig __unused;
1233 {
1234 
1235 	siginfo_p = 1;
1236 }
1237 
1238 static void
1239 check_status()
1240 {
1241 
1242 	if (siginfo_p) {
1243 		siginfo_p = 0;
1244 		(void)fprintf(stderr, "\r%ld/%ld packets received (%.0f%%)",
1245 		    nreceived, ntransmitted,
1246 		    ntransmitted ? nreceived * 100.0 / ntransmitted : 0.0);
1247 		if (nreceived && timing)
1248 			(void)fprintf(stderr, " %.3f min / %.3f avg / %.3f max",
1249 			    tmin, tsum / (nreceived + nrepeats), tmax);
1250 		(void)fprintf(stderr, "\n");
1251 	}
1252 }
1253 
1254 /*
1255  * finish --
1256  *	Print out statistics, and give up.
1257  */
1258 static void
1259 finish()
1260 {
1261 
1262 	(void)signal(SIGINT, SIG_IGN);
1263 	(void)signal(SIGALRM, SIG_IGN);
1264 	(void)putchar('\n');
1265 	(void)fflush(stdout);
1266 	(void)printf("--- %s ping statistics ---\n", hostname);
1267 	(void)printf("%ld packets transmitted, ", ntransmitted);
1268 	(void)printf("%ld packets received, ", nreceived);
1269 	if (nrepeats)
1270 		(void)printf("+%ld duplicates, ", nrepeats);
1271 	if (ntransmitted) {
1272 		if (nreceived > ntransmitted)
1273 			(void)printf("-- somebody's printing up packets!");
1274 		else
1275 			(void)printf("%d%% packet loss",
1276 			    (int)(((ntransmitted - nreceived) * 100) /
1277 			    ntransmitted));
1278 	}
1279 	(void)putchar('\n');
1280 	if (nreceived && timing) {
1281 		double n = nreceived + nrepeats;
1282 		double avg = tsum / n;
1283 		double vari = tsumsq / n - avg * avg;
1284 		(void)printf(
1285 		    "round-trip min/avg/max/stddev = %.3f/%.3f/%.3f/%.3f ms\n",
1286 		    tmin, avg, tmax, sqrt(vari));
1287 	}
1288 
1289 	if (nreceived)
1290 		exit(0);
1291 	else
1292 		exit(2);
1293 }
1294 
1295 #ifdef notdef
1296 static char *ttab[] = {
1297 	"Echo Reply",		/* ip + seq + udata */
1298 	"Dest Unreachable",	/* net, host, proto, port, frag, sr + IP */
1299 	"Source Quench",	/* IP */
1300 	"Redirect",		/* redirect type, gateway, + IP  */
1301 	"Echo",
1302 	"Time Exceeded",	/* transit, frag reassem + IP */
1303 	"Parameter Problem",	/* pointer + IP */
1304 	"Timestamp",		/* id + seq + three timestamps */
1305 	"Timestamp Reply",	/* " */
1306 	"Info Request",		/* id + sq */
1307 	"Info Reply"		/* " */
1308 };
1309 #endif
1310 
1311 /*
1312  * pr_icmph --
1313  *	Print a descriptive string about an ICMP header.
1314  */
1315 static void
1316 pr_icmph(icp)
1317 	struct icmp *icp;
1318 {
1319 
1320 	switch(icp->icmp_type) {
1321 	case ICMP_ECHOREPLY:
1322 		(void)printf("Echo Reply\n");
1323 		/* XXX ID + Seq + Data */
1324 		break;
1325 	case ICMP_UNREACH:
1326 		switch(icp->icmp_code) {
1327 		case ICMP_UNREACH_NET:
1328 			(void)printf("Destination Net Unreachable\n");
1329 			break;
1330 		case ICMP_UNREACH_HOST:
1331 			(void)printf("Destination Host Unreachable\n");
1332 			break;
1333 		case ICMP_UNREACH_PROTOCOL:
1334 			(void)printf("Destination Protocol Unreachable\n");
1335 			break;
1336 		case ICMP_UNREACH_PORT:
1337 			(void)printf("Destination Port Unreachable\n");
1338 			break;
1339 		case ICMP_UNREACH_NEEDFRAG:
1340 			(void)printf("frag needed and DF set (MTU %d)\n",
1341 					ntohs(icp->icmp_nextmtu));
1342 			break;
1343 		case ICMP_UNREACH_SRCFAIL:
1344 			(void)printf("Source Route Failed\n");
1345 			break;
1346 		case ICMP_UNREACH_FILTER_PROHIB:
1347 			(void)printf("Communication prohibited by filter\n");
1348 			break;
1349 		default:
1350 			(void)printf("Dest Unreachable, Bad Code: %d\n",
1351 			    icp->icmp_code);
1352 			break;
1353 		}
1354 		/* Print returned IP header information */
1355 #ifndef icmp_data
1356 		pr_retip(&icp->icmp_ip);
1357 #else
1358 		pr_retip((struct ip *)icp->icmp_data);
1359 #endif
1360 		break;
1361 	case ICMP_SOURCEQUENCH:
1362 		(void)printf("Source Quench\n");
1363 #ifndef icmp_data
1364 		pr_retip(&icp->icmp_ip);
1365 #else
1366 		pr_retip((struct ip *)icp->icmp_data);
1367 #endif
1368 		break;
1369 	case ICMP_REDIRECT:
1370 		switch(icp->icmp_code) {
1371 		case ICMP_REDIRECT_NET:
1372 			(void)printf("Redirect Network");
1373 			break;
1374 		case ICMP_REDIRECT_HOST:
1375 			(void)printf("Redirect Host");
1376 			break;
1377 		case ICMP_REDIRECT_TOSNET:
1378 			(void)printf("Redirect Type of Service and Network");
1379 			break;
1380 		case ICMP_REDIRECT_TOSHOST:
1381 			(void)printf("Redirect Type of Service and Host");
1382 			break;
1383 		default:
1384 			(void)printf("Redirect, Bad Code: %d", icp->icmp_code);
1385 			break;
1386 		}
1387 		(void)printf("(New addr: %s)\n", inet_ntoa(icp->icmp_gwaddr));
1388 #ifndef icmp_data
1389 		pr_retip(&icp->icmp_ip);
1390 #else
1391 		pr_retip((struct ip *)icp->icmp_data);
1392 #endif
1393 		break;
1394 	case ICMP_ECHO:
1395 		(void)printf("Echo Request\n");
1396 		/* XXX ID + Seq + Data */
1397 		break;
1398 	case ICMP_TIMXCEED:
1399 		switch(icp->icmp_code) {
1400 		case ICMP_TIMXCEED_INTRANS:
1401 			(void)printf("Time to live exceeded\n");
1402 			break;
1403 		case ICMP_TIMXCEED_REASS:
1404 			(void)printf("Frag reassembly time exceeded\n");
1405 			break;
1406 		default:
1407 			(void)printf("Time exceeded, Bad Code: %d\n",
1408 			    icp->icmp_code);
1409 			break;
1410 		}
1411 #ifndef icmp_data
1412 		pr_retip(&icp->icmp_ip);
1413 #else
1414 		pr_retip((struct ip *)icp->icmp_data);
1415 #endif
1416 		break;
1417 	case ICMP_PARAMPROB:
1418 		(void)printf("Parameter problem: pointer = 0x%02x\n",
1419 		    icp->icmp_hun.ih_pptr);
1420 #ifndef icmp_data
1421 		pr_retip(&icp->icmp_ip);
1422 #else
1423 		pr_retip((struct ip *)icp->icmp_data);
1424 #endif
1425 		break;
1426 	case ICMP_TSTAMP:
1427 		(void)printf("Timestamp\n");
1428 		/* XXX ID + Seq + 3 timestamps */
1429 		break;
1430 	case ICMP_TSTAMPREPLY:
1431 		(void)printf("Timestamp Reply\n");
1432 		/* XXX ID + Seq + 3 timestamps */
1433 		break;
1434 	case ICMP_IREQ:
1435 		(void)printf("Information Request\n");
1436 		/* XXX ID + Seq */
1437 		break;
1438 	case ICMP_IREQREPLY:
1439 		(void)printf("Information Reply\n");
1440 		/* XXX ID + Seq */
1441 		break;
1442 	case ICMP_MASKREQ:
1443 		(void)printf("Address Mask Request\n");
1444 		break;
1445 	case ICMP_MASKREPLY:
1446 		(void)printf("Address Mask Reply\n");
1447 		break;
1448 	case ICMP_ROUTERADVERT:
1449 		(void)printf("Router Advertisement\n");
1450 		break;
1451 	case ICMP_ROUTERSOLICIT:
1452 		(void)printf("Router Solicitation\n");
1453 		break;
1454 	default:
1455 		(void)printf("Bad ICMP type: %d\n", icp->icmp_type);
1456 	}
1457 }
1458 
1459 /*
1460  * pr_iph --
1461  *	Print an IP header with options.
1462  */
1463 static void
1464 pr_iph(ip)
1465 	struct ip *ip;
1466 {
1467 	u_char *cp;
1468 	int hlen;
1469 
1470 	hlen = ip->ip_hl << 2;
1471 	cp = (u_char *)ip + 20;		/* point to options */
1472 
1473 	(void)printf("Vr HL TOS  Len   ID Flg  off TTL Pro  cks      Src      Dst\n");
1474 	(void)printf(" %1x  %1x  %02x %04x %04x",
1475 	    ip->ip_v, ip->ip_hl, ip->ip_tos, ntohs(ip->ip_len),
1476 	    ntohs(ip->ip_id));
1477 	(void)printf("   %1lx %04lx",
1478 	    (u_long) (ntohl(ip->ip_off) & 0xe000) >> 13,
1479 	    (u_long) ntohl(ip->ip_off) & 0x1fff);
1480 	(void)printf("  %02x  %02x %04x", ip->ip_ttl, ip->ip_p,
1481 							    ntohs(ip->ip_sum));
1482 	(void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_src.s_addr));
1483 	(void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_dst.s_addr));
1484 	/* dump any option bytes */
1485 	while (hlen-- > 20) {
1486 		(void)printf("%02x", *cp++);
1487 	}
1488 	(void)putchar('\n');
1489 }
1490 
1491 /*
1492  * pr_addr --
1493  *	Return an ascii host address as a dotted quad and optionally with
1494  * a hostname.
1495  */
1496 static char *
1497 pr_addr(ina)
1498 	struct in_addr ina;
1499 {
1500 	struct hostent *hp;
1501 	static char buf[16 + 3 + MAXHOSTNAMELEN];
1502 
1503 	if ((options & F_NUMERIC) ||
1504 	    !(hp = gethostbyaddr((char *)&ina, 4, AF_INET)))
1505 		return inet_ntoa(ina);
1506 	else
1507 		(void)snprintf(buf, sizeof(buf), "%s (%s)", hp->h_name,
1508 		    inet_ntoa(ina));
1509 	return(buf);
1510 }
1511 
1512 /*
1513  * pr_retip --
1514  *	Dump some info on a returned (via ICMP) IP packet.
1515  */
1516 static void
1517 pr_retip(ip)
1518 	struct ip *ip;
1519 {
1520 	u_char *cp;
1521 	int hlen;
1522 
1523 	pr_iph(ip);
1524 	hlen = ip->ip_hl << 2;
1525 	cp = (u_char *)ip + hlen;
1526 
1527 	if (ip->ip_p == 6)
1528 		(void)printf("TCP: from port %u, to port %u (decimal)\n",
1529 		    (*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3)));
1530 	else if (ip->ip_p == 17)
1531 		(void)printf("UDP: from port %u, to port %u (decimal)\n",
1532 			(*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3)));
1533 }
1534 
1535 static char *
1536 pr_ntime (n_time timestamp)
1537 {
1538 	static char buf[10];
1539 	int hour, min, sec;
1540 
1541 	sec = ntohl(timestamp) / 1000;
1542 	hour = sec / 60 / 60;
1543 	min = (sec % (60 * 60)) / 60;
1544 	sec = (sec % (60 * 60)) % 60;
1545 
1546 	(void)snprintf(buf, sizeof(buf), "%02d:%02d:%02d", hour, min, sec);
1547 
1548 	return (buf);
1549 }
1550 
1551 static void
1552 fill(bp, patp)
1553 	char *bp, *patp;
1554 {
1555 	char *cp;
1556 	int pat[16];
1557 	u_int ii, jj, kk;
1558 
1559 	for (cp = patp; *cp; cp++) {
1560 		if (!isxdigit(*cp))
1561 			errx(EX_USAGE,
1562 			    "patterns must be specified as hex digits");
1563 
1564 	}
1565 	ii = sscanf(patp,
1566 	    "%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x",
1567 	    &pat[0], &pat[1], &pat[2], &pat[3], &pat[4], &pat[5], &pat[6],
1568 	    &pat[7], &pat[8], &pat[9], &pat[10], &pat[11], &pat[12],
1569 	    &pat[13], &pat[14], &pat[15]);
1570 
1571 	if (ii > 0)
1572 		for (kk = 0; kk <= maxpayload - (TIMEVAL_LEN + ii); kk += ii)
1573 			for (jj = 0; jj < ii; ++jj)
1574 				bp[jj + kk] = pat[jj];
1575 	if (!(options & F_QUIET)) {
1576 		(void)printf("PATTERN: 0x");
1577 		for (jj = 0; jj < ii; ++jj)
1578 			(void)printf("%02x", bp[jj] & 0xFF);
1579 		(void)printf("\n");
1580 	}
1581 }
1582 
1583 #if defined(IPSEC) && defined(IPSEC_POLICY_IPSEC)
1584 #define	SECOPT		" [-P policy]"
1585 #else
1586 #define	SECOPT		""
1587 #endif
1588 static void
1589 usage()
1590 {
1591 
1592 	(void)fprintf(stderr, "%s\n%s\n%s\n%s\n%s\n%s\n",
1593 "usage: ping [-AaDdfnoQqRrv] [-c count] [-i wait] [-l preload] [-M mask | time]",
1594 "            [-m ttl]" SECOPT " [-p pattern] [-S src_addr] [-s packetsize]",
1595 "            [-t timeout] [-z tos] host",
1596 "       ping [-AaDdfLnoQqRrv] [-c count] [-I iface] [-i wait] [-l preload]",
1597 "            [-M mask | time] [-m ttl]" SECOPT " [-p pattern] [-S src_addr]",
1598 "            [-s packetsize] [-T ttl] [-t timeout] [-z tos] mcast-group");
1599 	exit(EX_USAGE);
1600 }
1601