xref: /openbsd-src/sbin/ping/ping.c (revision d13be5d47e4149db2549a9828e244d59dbc43f15)
1 /*	$OpenBSD: ping.c,v 1.89 2011/06/21 17:31:07 mikeb Exp $	*/
2 /*	$NetBSD: ping.c,v 1.20 1995/08/11 22:37:58 cgd Exp $	*/
3 
4 /*
5  * Copyright (c) 1989, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  *
8  * This code is derived from software contributed to Berkeley by
9  * Mike Muuss.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  * 3. Neither the name of the University nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35 
36 /*
37  *			P I N G . C
38  *
39  * Using the InterNet Control Message Protocol (ICMP) "ECHO" facility,
40  * measure round-trip-delays and packet loss across network paths.
41  *
42  * Author -
43  *	Mike Muuss
44  *	U. S. Army Ballistic Research Laboratory
45  *	December, 1983
46  *
47  * Status -
48  *	Public Domain.  Distribution Unlimited.
49  * Bugs -
50  *	More statistics could always be gathered.
51  *	This program has to run SUID to ROOT to access the ICMP socket.
52  */
53 
54 #include <sys/param.h>
55 #include <sys/queue.h>
56 #include <sys/socket.h>
57 #include <sys/file.h>
58 #include <sys/time.h>
59 
60 #include <netinet/in_systm.h>
61 #include <netinet/in.h>
62 #include <netinet/ip.h>
63 #include <netinet/ip_icmp.h>
64 #include <netinet/ip_var.h>
65 #include <arpa/inet.h>
66 #include <netdb.h>
67 #include <signal.h>
68 #include <unistd.h>
69 #include <stdio.h>
70 #include <ctype.h>
71 #include <err.h>
72 #include <errno.h>
73 #include <string.h>
74 #include <stdlib.h>
75 
76 struct tvi {
77 	u_int	tv_sec;
78 	u_int	tv_usec;
79 };
80 
81 #define	DEFDATALEN	(64 - 8)		/* default data length */
82 #define	MAXIPLEN	60
83 #define	MAXICMPLEN	76
84 #define	MAXPAYLOAD	(IP_MAXPACKET - MAXIPLEN - 8) /* max ICMP payload size */
85 #define	MAXWAIT_DEFAULT	10			/* secs to wait for response */
86 #define	NROUTES		9			/* number of record route slots */
87 
88 #define	A(bit)		rcvd_tbl[(bit)>>3]	/* identify byte in array */
89 #define	B(bit)		(1 << ((bit) & 0x07))	/* identify bit in byte */
90 #define	SET(bit)	(A(bit) |= B(bit))
91 #define	CLR(bit)	(A(bit) &= (~B(bit)))
92 #define	TST(bit)	(A(bit) & B(bit))
93 
94 /* various options */
95 int options;
96 #define	F_FLOOD		0x0001
97 #define	F_INTERVAL	0x0002
98 #define	F_NUMERIC	0x0004
99 #define	F_PINGFILLED	0x0008
100 #define	F_QUIET		0x0010
101 #define	F_RROUTE	0x0020
102 #define	F_SO_DEBUG	0x0040
103 #define	F_SO_DONTROUTE	0x0080
104 #define	F_VERBOSE	0x0100
105 #define	F_SADDR		0x0200
106 #define	F_HDRINCL	0x0400
107 #define	F_TTL		0x0800
108 #define	F_SO_JUMBO	0x1000
109 #define	F_AUD_RECV	0x2000
110 #define	F_AUD_MISS	0x4000
111 
112 /* multicast options */
113 int moptions;
114 #define	MULTICAST_NOLOOP	0x001
115 #define	MULTICAST_TTL		0x002
116 #define	MULTICAST_IF		0x004
117 
118 /*
119  * MAX_DUP_CHK is the number of bits in received table, i.e. the maximum
120  * number of received sequence numbers we can keep track of.  Change 128
121  * to 8192 for complete accuracy...
122  */
123 #define	MAX_DUP_CHK	(8 * 128)
124 int mx_dup_ck = MAX_DUP_CHK;
125 char rcvd_tbl[MAX_DUP_CHK / 8];
126 
127 struct sockaddr_in whereto;	/* who to ping */
128 struct sockaddr_in whence;		/* Which interface we come from */
129 unsigned int datalen = DEFDATALEN;
130 int s;				/* socket file descriptor */
131 u_char outpackhdr[IP_MAXPACKET]; /* Max packet size = 65535 */
132 u_char *outpack = outpackhdr+sizeof(struct ip);
133 char BSPACE = '\b';		/* characters written for flood */
134 char DOT = '.';
135 char *hostname;
136 int ident;			/* process id to identify our packets */
137 
138 /* counters */
139 unsigned long npackets;		/* max packets to transmit */
140 unsigned long nreceived;	/* # of packets we got back */
141 unsigned long nrepeats;		/* number of duplicates */
142 unsigned long ntransmitted;	/* sequence # for outbound packets = #sent */
143 unsigned long nmissedmax = 1;	/* max value of ntransmitted - nreceived - 1 */
144 double interval = 1;		/* interval between packets */
145 struct itimerval interstr;	/* interval structure for use with setitimer */
146 
147 /* timing */
148 int timing;			/* flag to do timing */
149 unsigned int maxwait = MAXWAIT_DEFAULT;	/* max seconds to wait for response */
150 quad_t tmin = 999999999;	/* minimum round trip time in usec */
151 quad_t tmax = 0;		/* maximum round trip time in usec */
152 quad_t tsum = 0;		/* sum of all times in usec, for doing average */
153 quad_t tsumsq = 0;		/* sum of all times squared, for std. dev. */
154 
155 int bufspace = IP_MAXPACKET;
156 
157 void fill(char *, char *);
158 void catcher(int signo);
159 void prtsig(int signo);
160 void finish(int signo);
161 void summary(int, int);
162 int in_cksum(u_short *, int);
163 void pinger(void);
164 char *pr_addr(in_addr_t);
165 int check_icmph(struct ip *);
166 void pr_icmph(struct icmp *);
167 void pr_pack(char *, int, struct sockaddr_in *);
168 void pr_retip(struct ip *);
169 quad_t qsqrt(quad_t);
170 void pr_iph(struct ip *);
171 void usage(void);
172 
173 int
174 main(int argc, char *argv[])
175 {
176 	struct timeval timeout;
177 	struct hostent *hp;
178 	struct sockaddr_in *to;
179 	struct in_addr saddr;
180 	int i, ch, hold = 1, packlen, preload, maxsize, df = 0, tos = 0;
181 	u_char *datap, *packet, ttl = MAXTTL, loop = 1;
182 	char *target, hnamebuf[MAXHOSTNAMELEN];
183 #ifdef IP_OPTIONS
184 	char rspace[3 + 4 * NROUTES + 1];	/* record route space */
185 #endif
186 	socklen_t maxsizelen;
187 	const char *errstr;
188 	fd_set *fdmaskp;
189 	size_t fdmasks;
190 	uid_t uid;
191 	u_int rtableid;
192 
193 	if ((s = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP)) < 0)
194 		err(1, "socket");
195 
196 	/* revoke privs */
197 	uid = getuid();
198 	if (setresuid(uid, uid, uid) == -1)
199 		err(1, "setresuid");
200 
201 	preload = 0;
202 	datap = &outpack[8 + sizeof(struct tvi)];
203 	while ((ch = getopt(argc, argv,
204 	    "DEI:LRS:c:defi:jl:np:qrs:T:t:V:vw:")) != -1)
205 		switch(ch) {
206 		case 'c':
207 			npackets = (unsigned long)strtonum(optarg, 0,
208 			    INT_MAX, &errstr);
209 			if (errstr)
210 				errx(1,
211 				    "number of packets to transmit is %s: %s",
212 				    errstr, optarg);
213 			break;
214 		case 'D':
215 			options |= F_HDRINCL;
216 			df = 1;
217 			break;
218 		case 'd':
219 			options |= F_SO_DEBUG;
220 			break;
221 		case 'E':
222 			options |= F_AUD_MISS;
223 			break;
224 		case 'e':
225 			options |= F_AUD_RECV;
226 			break;
227 		case 'f':
228 			if (getuid())
229 				errx(1, "%s", strerror(EPERM));
230 			options |= F_FLOOD;
231 			setbuf(stdout, (char *)NULL);
232 			break;
233 		case 'I':
234 		case 'S':	/* deprecated */
235 			if (inet_aton(optarg, &saddr) == 0) {
236 				if ((hp = gethostbyname(optarg)) == NULL)
237 					errx(1, "bad interface address: %s",
238 					    optarg);
239 				memcpy(&saddr, hp->h_addr, sizeof(saddr));
240 			}
241 			options |= F_SADDR;
242 			break;
243 		case 'i':		/* wait between sending packets */
244 			interval = strtod(optarg, NULL);
245 
246 			if (interval <= 0 || interval >= INT_MAX)
247 				errx(1, "bad timing interval: %s", optarg);
248 
249 			if (interval < 1)
250 				if (getuid())
251 					errx(1, "%s: only root may use interval < 1s",
252 					    strerror(EPERM));
253 
254 			if (interval < 0.01)
255 				interval = 0.01;
256 
257 			options |= F_INTERVAL;
258 			break;
259 		case 'j':
260 			options |= F_SO_JUMBO;
261 			break;
262 		case 'L':
263 			moptions |= MULTICAST_NOLOOP;
264 			loop = 0;
265 			break;
266 		case 'l':
267 			if (getuid())
268 				errx(1, "%s", strerror(EPERM));
269 			preload = (int)strtonum(optarg, 1, INT_MAX, &errstr);
270 			if (errstr)
271 				errx(1, "preload value is %s: %s",
272 				    errstr, optarg);
273 			break;
274 		case 'n':
275 			options |= F_NUMERIC;
276 			break;
277 		case 'p':		/* fill buffer with user pattern */
278 			options |= F_PINGFILLED;
279 			fill((char *)datap, optarg);
280 				break;
281 		case 'q':
282 			options |= F_QUIET;
283 			break;
284 		case 'R':
285 			options |= F_RROUTE;
286 			break;
287 		case 'r':
288 			options |= F_SO_DONTROUTE;
289 			break;
290 		case 's':		/* size of packet to send */
291 			datalen = (unsigned int)strtonum(optarg, 0, MAXPAYLOAD, &errstr);
292 			if (errstr)
293 				errx(1, "packet size is %s: %s",
294 				    errstr, optarg);
295 			break;
296 		case 'T':
297 			options |= F_HDRINCL;
298 			tos = (int)strtonum(optarg, 0, 0xff, &errstr);
299 			if (errstr)
300 				errx(1, "tos value is %s: %s", errstr, optarg);
301 			break;
302 		case 't':
303 			options |= F_TTL;
304 			ttl = (u_char)strtonum(optarg, 1, 255, &errstr);
305 			if (errstr)
306 				errx(1, "ttl value is %s: %s", errstr, optarg);
307 			break;
308 		case 'V':
309 			rtableid = (unsigned int)strtonum(optarg, 0,
310 			    RT_TABLEID_MAX, &errstr);
311 			if (errstr)
312 				errx(1, "rtable value is %s: %s",
313 				    errstr, optarg);
314 
315 			if (setsockopt(s, SOL_SOCKET, SO_RTABLE, &rtableid,
316 			    sizeof(rtableid)) == -1)
317 				err(1, "setsockopt SO_RTABLE");
318 			break;
319 		case 'v':
320 			options |= F_VERBOSE;
321 			break;
322 		case 'w':
323 			maxwait = (unsigned int)strtonum(optarg, 1, INT_MAX,
324 			    &errstr);
325 			if (errstr)
326 				errx(1, "maxwait value is %s: %s",
327 				    errstr, optarg);
328 			break;
329 		default:
330 			usage();
331 		}
332 	argc -= optind;
333 	argv += optind;
334 
335 	if (argc != 1)
336 		usage();
337 
338 	memset(&interstr, 0, sizeof(interstr));
339 
340 	interstr.it_value.tv_sec = (long) interval;
341 	interstr.it_value.tv_usec =
342 		(long) ((interval - interstr.it_value.tv_sec) * 1000000);
343 
344 	target = *argv;
345 
346 	memset(&whereto, 0, sizeof(whereto));
347 	to = &whereto;
348 	to->sin_len = sizeof(struct sockaddr_in);
349 	to->sin_family = AF_INET;
350 	if (inet_aton(target, &to->sin_addr) != 0)
351 		hostname = target;
352 	else {
353 		hp = gethostbyname(target);
354 		if (!hp)
355 			errx(1, "unknown host: %s", target);
356 		to->sin_family = hp->h_addrtype;
357 		memcpy(&to->sin_addr, hp->h_addr, (size_t)hp->h_length);
358 		(void)strlcpy(hnamebuf, hp->h_name, sizeof(hnamebuf));
359 		hostname = hnamebuf;
360 	}
361 
362 	if (options & F_FLOOD && options & F_INTERVAL)
363 		errx(1, "-f and -i options are incompatible");
364 
365 	if ((options & F_FLOOD) && (options & (F_AUD_RECV | F_AUD_MISS)))
366 		warnx("No audible output for flood pings");
367 
368 	if (datalen >= sizeof(struct tvi))	/* can we time transfer */
369 		timing = 1;
370 	packlen = datalen + MAXIPLEN + MAXICMPLEN;
371 	if (!(packet = malloc((size_t)packlen)))
372 		err(1, "malloc");
373 	if (!(options & F_PINGFILLED))
374 		for (i = sizeof(struct tvi); i < datalen; ++i)
375 			*datap++ = i;
376 
377 	ident = getpid() & 0xFFFF;
378 
379 	if (options & F_SADDR) {
380 		if (IN_MULTICAST(ntohl(to->sin_addr.s_addr)))
381 			moptions |= MULTICAST_IF;
382 		else {
383 			memset(&whence, 0, sizeof(whence));
384 			whence.sin_len = sizeof(whence);
385 			whence.sin_family = AF_INET;
386 			memcpy(&whence.sin_addr.s_addr, &saddr, sizeof(saddr));
387 			if (bind(s, (struct sockaddr *)&whence,
388 			    sizeof(whence)) < 0)
389 				err(1, "bind");
390 		}
391 	}
392 
393 	if (options & F_SO_DEBUG)
394 		(void)setsockopt(s, SOL_SOCKET, SO_DEBUG, &hold,
395 		    sizeof(hold));
396 	if (options & F_SO_DONTROUTE)
397 		(void)setsockopt(s, SOL_SOCKET, SO_DONTROUTE, &hold,
398 		    sizeof(hold));
399 	if (options & F_SO_JUMBO)
400 		(void)setsockopt(s, SOL_SOCKET, SO_JUMBO, &hold,
401 		    sizeof(hold));
402 
403 	if (options & F_TTL) {
404 		if (IN_MULTICAST(ntohl(to->sin_addr.s_addr)))
405 			moptions |= MULTICAST_TTL;
406 		else
407 			options |= F_HDRINCL;
408 	}
409 
410 	if (options & F_RROUTE && options & F_HDRINCL)
411 		errx(1, "-R option and -D or -T, or -t to unicast destinations"
412 		    " are incompatible");
413 
414 	if (options & F_HDRINCL) {
415 		struct ip *ip = (struct ip *)outpackhdr;
416 
417 		setsockopt(s, IPPROTO_IP, IP_HDRINCL, &hold, sizeof(hold));
418 		ip->ip_v = IPVERSION;
419 		ip->ip_hl = sizeof(struct ip) >> 2;
420 		ip->ip_tos = tos;
421 		ip->ip_id = 0;
422 		ip->ip_off = htons(df ? IP_DF : 0);
423 		ip->ip_ttl = ttl;
424 		ip->ip_p = IPPROTO_ICMP;
425 		if (options & F_SADDR)
426 			ip->ip_src = saddr;
427 		else
428 			ip->ip_src.s_addr = INADDR_ANY;
429 		ip->ip_dst = to->sin_addr;
430 	}
431 
432 	/* record route option */
433 	if (options & F_RROUTE) {
434 		if (IN_MULTICAST(ntohl(to->sin_addr.s_addr)))
435 			errx(1, "record route not valid to multicast destinations");
436 #ifdef IP_OPTIONS
437 		memset(rspace, 0, sizeof(rspace));
438 		rspace[IPOPT_OPTVAL] = IPOPT_RR;
439 		rspace[IPOPT_OLEN] = sizeof(rspace)-1;
440 		rspace[IPOPT_OFFSET] = IPOPT_MINOFF;
441 		if (setsockopt(s, IPPROTO_IP, IP_OPTIONS, rspace,
442 		    sizeof(rspace)) < 0) {
443 			perror("ping: record route");
444 			exit(1);
445 		}
446 #else
447 		errx(1, "record route not available in this implementation");
448 #endif /* IP_OPTIONS */
449 	}
450 
451 	if ((moptions & MULTICAST_NOLOOP) &&
452 	    setsockopt(s, IPPROTO_IP, IP_MULTICAST_LOOP, &loop,
453 	    sizeof(loop)) < 0)
454 		err(1, "setsockopt IP_MULTICAST_LOOP");
455 	if ((moptions & MULTICAST_TTL) &&
456 	    setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL, &ttl,
457 	    sizeof(ttl)) < 0)
458 		err(1, "setsockopt IP_MULTICAST_TTL");
459 	if ((moptions & MULTICAST_IF) &&
460 	    setsockopt(s, IPPROTO_IP, IP_MULTICAST_IF, &saddr,
461 	    sizeof(saddr)) < 0)
462 		err(1, "setsockopt IP_MULTICAST_IF");
463 
464 	/*
465 	 * When trying to send large packets, you must increase the
466 	 * size of both the send and receive buffers...
467 	 */
468 	maxsizelen = sizeof maxsize;
469 	if (getsockopt(s, SOL_SOCKET, SO_SNDBUF, &maxsize, &maxsizelen) < 0)
470 		err(1, "getsockopt");
471 	if (maxsize < packlen &&
472 	    setsockopt(s, SOL_SOCKET, SO_SNDBUF, &packlen, sizeof(maxsize)) < 0)
473 		err(1, "setsockopt");
474 
475 	/*
476 	 * When pinging the broadcast address, you can get a lot of answers.
477 	 * Doing something so evil is useful if you are trying to stress the
478 	 * ethernet, or just want to fill the arp cache to get some stuff for
479 	 * /etc/ethers.
480 	 */
481 	while (setsockopt(s, SOL_SOCKET, SO_RCVBUF,
482 	    (void*)&bufspace, sizeof(bufspace)) < 0) {
483 		if ((bufspace -= 1024) <= 0)
484 			err(1, "Cannot set the receive buffer size");
485 	}
486 	if (bufspace < IP_MAXPACKET)
487 		warnx("Could only allocate a receive buffer of %i bytes (default %i)",
488 		    bufspace, IP_MAXPACKET);
489 
490 	if (to->sin_family == AF_INET)
491 		(void)printf("PING %s (%s): %d data bytes\n", hostname,
492 		    inet_ntoa(*(struct in_addr *)&to->sin_addr.s_addr),
493 		    datalen);
494 	else
495 		(void)printf("PING %s: %d data bytes\n", hostname, datalen);
496 
497 	(void)signal(SIGINT, finish);
498 	(void)signal(SIGALRM, catcher);
499 #ifdef SIGINFO
500 	(void)signal(SIGINFO, prtsig);
501 #endif
502 
503 	while (preload--)		/* fire off them quickies */
504 		pinger();
505 
506 	if ((options & F_FLOOD) == 0)
507 		catcher(0);		/* start things going */
508 
509 	fdmasks = howmany(s+1, NFDBITS) * sizeof(fd_mask);
510 	if ((fdmaskp = (fd_set *)malloc(fdmasks)) == NULL)
511 		err(1, "malloc");
512 
513 	for (;;) {
514 		struct sockaddr_in from;
515 		sigset_t omask, nmask;
516 		socklen_t fromlen;
517 		int cc;
518 
519 		if (options & F_FLOOD) {
520 			pinger();
521 			timeout.tv_sec = 0;
522 			timeout.tv_usec = 10000;
523 			memset(fdmaskp, 0, fdmasks);
524 			FD_SET(s, fdmaskp);
525 			if (select(s + 1, (fd_set *)fdmaskp, (fd_set *)NULL,
526 			    (fd_set *)NULL, &timeout) < 1)
527 				continue;
528 		}
529 		fromlen = sizeof(from);
530 		if ((cc = recvfrom(s, packet, packlen, 0,
531 		    (struct sockaddr *)&from, &fromlen)) < 0) {
532 			if (errno == EINTR)
533 				continue;
534 			perror("ping: recvfrom");
535 			continue;
536 		}
537 		sigemptyset(&nmask);
538 		sigaddset(&nmask, SIGALRM);
539 		sigprocmask(SIG_BLOCK, &nmask, &omask);
540 		pr_pack((char *)packet, cc, &from);
541 		sigprocmask(SIG_SETMASK, &omask, NULL);
542 		if (npackets && nreceived >= npackets)
543 			break;
544 	}
545 	free(fdmaskp);
546 	finish(0);
547 	/* NOTREACHED */
548 	exit(0);	/* Make the compiler happy */
549 }
550 
551 /*
552  * catcher --
553  *	This routine causes another PING to be transmitted, and then
554  * schedules another SIGALRM for 1 second from now.
555  *
556  * bug --
557  *	Our sense of time will slowly skew (i.e., packets will not be
558  * launched exactly at 1-second intervals).  This does not affect the
559  * quality of the delay and loss statistics.
560  */
561 /* ARGSUSED */
562 void
563 catcher(int signo)
564 {
565 	int save_errno = errno;
566 	unsigned int waittime;
567 
568 	pinger();
569 	(void)signal(SIGALRM, catcher);
570 	if (!npackets || ntransmitted < npackets)
571 		setitimer(ITIMER_REAL, &interstr, (struct itimerval *)0);
572 	else {
573 		if (nreceived) {
574 			waittime = 2 * tmax / 1000000;
575 			if (!waittime)
576 				waittime = 1;
577 		} else
578 			waittime = maxwait;
579 		(void)signal(SIGALRM, finish);
580 		(void)alarm(waittime);
581 	}
582 	if (ntransmitted - nreceived - 1 > nmissedmax) {
583 		nmissedmax = ntransmitted - nreceived - 1;
584 		if (!(options & F_FLOOD) && (options & F_AUD_MISS))
585 			(void)fputc('\a', stderr);
586 	}
587 	errno = save_errno;
588 }
589 
590 /*
591  * Print statistics when SIGINFO is received.
592  */
593 /* ARGSUSED */
594 void
595 prtsig(int signo)
596 {
597 	int save_errno = errno;
598 
599 	summary(0, 1);
600 	errno = save_errno;
601 }
602 
603 /*
604  * pinger --
605  *	Compose and transmit an ICMP ECHO REQUEST packet.  The IP packet
606  * will be added on by the kernel.  The ID field is our UNIX process ID,
607  * and the sequence number is an ascending integer.  The first 8 bytes
608  * of the data portion are used to hold a UNIX "timeval" struct in VAX
609  * byte-order, to compute the round-trip time.
610  */
611 void
612 pinger(void)
613 {
614 	struct icmp *icp;
615 	char buf[8192];
616 	int cc, i;
617 	u_char *packet = outpack;
618 
619 	icp = (struct icmp *)outpack;
620 	icp->icmp_type = ICMP_ECHO;
621 	icp->icmp_code = 0;
622 	icp->icmp_cksum = 0;
623 	icp->icmp_seq = htons(ntransmitted);
624 	icp->icmp_id = ident;			/* ID */
625 
626 	CLR(ntohs(icp->icmp_seq) % mx_dup_ck);
627 
628 	if (timing) {
629 		struct timeval tv;
630 		struct tvi tvi;
631 
632 		(void)gettimeofday(&tv, (struct timezone *)NULL);
633 		tvi.tv_sec = htonl(tv.tv_sec);
634 		tvi.tv_usec = htonl(tv.tv_usec);
635 		memcpy(&outpack[8], &tvi, sizeof tvi);
636 	}
637 
638 	cc = datalen + 8;			/* skips ICMP portion */
639 
640 	/* compute ICMP checksum here */
641 	icp->icmp_cksum = in_cksum((u_short *)icp, cc);
642 
643 	if (options & F_HDRINCL) {
644 		struct ip *ip = (struct ip *)outpackhdr;
645 
646 		packet = (u_char *)ip;
647 		cc += sizeof(struct ip);
648 		ip->ip_len = htons(cc);
649 		ip->ip_sum = in_cksum((u_short *)outpackhdr, cc);
650 	}
651 
652 	i = sendto(s, packet, cc, 0, (struct sockaddr *)&whereto,
653 	    sizeof(whereto));
654 
655 	if (i < 0 || i != cc)  {
656 		if (i < 0)
657 			perror("ping: sendto");
658 		snprintf(buf, sizeof buf, "ping: wrote %s %d chars, ret=%d\n",
659 		    hostname, cc, i);
660 		write(STDOUT_FILENO, buf, strlen(buf));
661 	}
662 	if (!(options & F_QUIET) && options & F_FLOOD)
663 		(void)write(STDOUT_FILENO, &DOT, 1);
664 
665 	ntransmitted++;
666 }
667 
668 /*
669  * pr_pack --
670  *	Print out the packet, if it came from us.  This logic is necessary
671  * because ALL readers of the ICMP socket get a copy of ALL ICMP packets
672  * which arrive ('tis only fair).  This permits multiple copies of this
673  * program to be run without having intermingled output (or statistics!).
674  */
675 void
676 pr_pack(char *buf, int cc, struct sockaddr_in *from)
677 {
678 	struct icmp *icp;
679 	in_addr_t l;
680 	u_int i, j;
681 	u_char *cp, *dp;
682 	static int old_rrlen;
683 	static char old_rr[MAX_IPOPTLEN];
684 	struct ip *ip, *ip2;
685 	struct timeval tv, tp;
686 	char *pkttime;
687 	quad_t triptime = 0;
688 	int hlen, hlen2, dupflag;
689 
690 	(void)gettimeofday(&tv, (struct timezone *)NULL);
691 
692 	/* Check the IP header */
693 	ip = (struct ip *)buf;
694 	hlen = ip->ip_hl << 2;
695 	if (cc < hlen + ICMP_MINLEN) {
696 		if (options & F_VERBOSE)
697 			warnx("packet too short (%d bytes) from %s", cc,
698 			    inet_ntoa(*(struct in_addr *)&from->sin_addr.s_addr));
699 		return;
700 	}
701 
702 	/* Now the ICMP part */
703 	cc -= hlen;
704 	icp = (struct icmp *)(buf + hlen);
705 	if (icp->icmp_type == ICMP_ECHOREPLY) {
706 		if (icp->icmp_id != ident)
707 			return;			/* 'Twas not our ECHO */
708 		++nreceived;
709 		if (timing) {
710 			struct tvi tvi;
711 
712 #ifndef icmp_data
713 			pkttime = (char *)&icp->icmp_ip;
714 #else
715 			pkttime = (char *)icp->icmp_data;
716 #endif
717 			memcpy(&tvi, pkttime, sizeof tvi);
718 			tp.tv_sec = ntohl(tvi.tv_sec);
719 			tp.tv_usec = ntohl(tvi.tv_usec);
720 
721 			timersub(&tv, &tp, &tv);
722 			triptime = (tv.tv_sec * 1000000) + tv.tv_usec;
723 			tsum += triptime;
724 			tsumsq += triptime * triptime;
725 			if (triptime < tmin)
726 				tmin = triptime;
727 			if (triptime > tmax)
728 				tmax = triptime;
729 		}
730 
731 		if (TST(ntohs(icp->icmp_seq) % mx_dup_ck)) {
732 			++nrepeats;
733 			--nreceived;
734 			dupflag = 1;
735 		} else {
736 			SET(ntohs(icp->icmp_seq) % mx_dup_ck);
737 			dupflag = 0;
738 		}
739 
740 		if (options & F_QUIET)
741 			return;
742 
743 		if (options & F_FLOOD)
744 			(void)write(STDOUT_FILENO, &BSPACE, 1);
745 		else {
746 			(void)printf("%d bytes from %s: icmp_seq=%u", cc,
747 			    inet_ntoa(*(struct in_addr *)&from->sin_addr.s_addr),
748 			    ntohs(icp->icmp_seq));
749 			(void)printf(" ttl=%d", ip->ip_ttl);
750 			if (timing)
751 				(void)printf(" time=%d.%03d ms",
752 				    (int)(triptime / 1000),
753 				    (int)(triptime % 1000));
754 			if (dupflag)
755 				(void)printf(" (DUP!)");
756 			/* check the data */
757 			if (cc - 8 < datalen)
758 				(void)printf(" (TRUNC!)");
759 			cp = (u_char *)&icp->icmp_data[sizeof(struct tvi)];
760 			dp = &outpack[8 + sizeof(struct tvi)];
761 			for (i = 8 + sizeof(struct tvi); i < cc && i < datalen;
762 			    ++i, ++cp, ++dp) {
763 				if (*cp != *dp) {
764 					(void)printf("\nwrong data byte #%d "
765 					    "should be 0x%x but was 0x%x",
766 					    i - 8, *dp, *cp);
767 					cp = (u_char *)&icp->icmp_data[0];
768 					for (i = 8; i < cc && i < datalen;
769 					     ++i, ++cp) {
770 						if ((i % 32) == 8)
771 							(void)printf("\n\t");
772 						(void)printf("%x ", *cp);
773 					}
774 					break;
775 				}
776 			}
777 		}
778 	} else {
779 		/* We've got something other than an ECHOREPLY */
780 		if (!(options & F_VERBOSE))
781 			return;
782 		ip2 = (struct ip *)(buf + hlen + sizeof (struct icmp));
783 		hlen2 = ip2->ip_hl << 2;
784 		if (cc >= hlen2 + 8 && check_icmph(ip2) != 1)
785 			return;
786 		(void)printf("%d bytes from %s: ", cc,
787 		    pr_addr(from->sin_addr.s_addr));
788 		pr_icmph(icp);
789 	}
790 
791 	/* Display any IP options */
792 	cp = (u_char *)buf + sizeof(struct ip);
793 
794 	for (; hlen > (int)sizeof(struct ip); --hlen, ++cp)
795 		switch (*cp) {
796 		case IPOPT_EOL:
797 			hlen = 0;
798 			break;
799 		case IPOPT_LSRR:
800 			(void)printf("\nLSRR: ");
801 			hlen -= 2;
802 			j = *++cp;
803 			++cp;
804 			i = 0;
805 			if (j > IPOPT_MINOFF) {
806 				for (;;) {
807 					l = *++cp;
808 					l = (l<<8) + *++cp;
809 					l = (l<<8) + *++cp;
810 					l = (l<<8) + *++cp;
811 					if (l == 0)
812 						(void)printf("\t0.0.0.0");
813 					else
814 						(void)printf("\t%s",
815 						    pr_addr(ntohl(l)));
816 					hlen -= 4;
817 					j -= 4;
818 					i += 4;
819 					if (j <= IPOPT_MINOFF)
820 						break;
821 					if (i >= MAX_IPOPTLEN) {
822 						(void)printf("\t(truncated route)");
823 						break;
824 					}
825 					(void)putchar('\n');
826 				}
827 			}
828 			break;
829 		case IPOPT_RR:
830 			j = *++cp;		/* get length */
831 			i = *++cp;		/* and pointer */
832 			hlen -= 2;
833 			if (i > j)
834 				i = j;
835 			i -= IPOPT_MINOFF;
836 			if (i <= 0)
837 				continue;
838 			if (i == old_rrlen &&
839 			    cp == (u_char *)buf + sizeof(struct ip) + 2 &&
840 			    !memcmp(cp, old_rr, i) &&
841 			    !(options & F_FLOOD)) {
842 				(void)printf("\t(same route)");
843 				i = ((i + 3) / 4) * 4;
844 				hlen -= i;
845 				cp += i;
846 				break;
847 			}
848 			if (i < MAX_IPOPTLEN) {
849 				old_rrlen = i;
850 				memcpy(old_rr, cp, i);
851 			} else
852 				old_rrlen = 0;
853 
854 			(void)printf("\nRR: ");
855 			j = 0;
856 			for (;;) {
857 				l = *++cp;
858 				l = (l<<8) + *++cp;
859 				l = (l<<8) + *++cp;
860 				l = (l<<8) + *++cp;
861 				if (l == 0)
862 					(void)printf("\t0.0.0.0");
863 				else
864 					(void)printf("\t%s", pr_addr(ntohl(l)));
865 				hlen -= 4;
866 				i -= 4;
867 				j += 4;
868 				if (i <= 0)
869 					break;
870 				if (j >= MAX_IPOPTLEN) {
871 					(void)printf("\t(truncated route)");
872 					break;
873 				}
874 				(void)putchar('\n');
875 			}
876 			break;
877 		case IPOPT_NOP:
878 			(void)printf("\nNOP");
879 			break;
880 		default:
881 			(void)printf("\nunknown option %x", *cp);
882 			hlen = hlen - (cp[IPOPT_OLEN] - 1);
883 			cp = cp + (cp[IPOPT_OLEN] - 1);
884 			break;
885 		}
886 	if (!(options & F_FLOOD)) {
887 		(void)putchar('\n');
888 		(void)fflush(stdout);
889 		if (options & F_AUD_RECV)
890 			(void)fputc('\a', stderr);
891 	}
892 }
893 
894 /*
895  * in_cksum --
896  *	Checksum routine for Internet Protocol family headers (C Version)
897  */
898 int
899 in_cksum(u_short *addr, int len)
900 {
901 	int nleft = len;
902 	u_short *w = addr;
903 	int sum = 0;
904 	u_short answer = 0;
905 
906 	/*
907 	 * Our algorithm is simple, using a 32 bit accumulator (sum), we add
908 	 * sequential 16 bit words to it, and at the end, fold back all the
909 	 * carry bits from the top 16 bits into the lower 16 bits.
910 	 */
911 	while (nleft > 1)  {
912 		sum += *w++;
913 		nleft -= 2;
914 	}
915 
916 	/* mop up an odd byte, if necessary */
917 	if (nleft == 1) {
918 		*(u_char *)(&answer) = *(u_char *)w ;
919 		sum += answer;
920 	}
921 
922 	/* add back carry outs from top 16 bits to low 16 bits */
923 	sum = (sum >> 16) + (sum & 0xffff);	/* add hi 16 to low 16 */
924 	sum += (sum >> 16);			/* add carry */
925 	answer = ~sum;				/* truncate to 16 bits */
926 	return(answer);
927 }
928 
929 void
930 summary(int header, int insig)
931 {
932 	char buf[8192], buft[8192];
933 
934 	buf[0] = '\0';
935 
936 	if (!insig) {
937 		(void)putchar('\r');
938 		(void)fflush(stdout);
939 	} else
940 		strlcat(buf, "\r", sizeof buf);
941 
942 	if (header) {
943 		snprintf(buft, sizeof buft, "--- %s ping statistics ---\n",
944 		    hostname);
945 		strlcat(buf, buft, sizeof buf);
946 	}
947 
948 	snprintf(buft, sizeof buft, "%ld packets transmitted, ", ntransmitted);
949 	strlcat(buf, buft, sizeof buf);
950 	snprintf(buft, sizeof buft, "%ld packets received, ", nreceived);
951 	strlcat(buf, buft, sizeof buf);
952 
953 	if (nrepeats) {
954 		snprintf(buft, sizeof buft, "%ld duplicates, ", nrepeats);
955 		strlcat(buf, buft, sizeof buf);
956 	}
957 	if (ntransmitted) {
958 		if (nreceived > ntransmitted)
959 			snprintf(buft, sizeof buft,
960 			    "-- somebody's duplicating packets!");
961 		else
962 			snprintf(buft, sizeof buft, "%.1f%% packet loss",
963 			    ((((double)ntransmitted - nreceived) * 100) /
964 			    ntransmitted));
965 		strlcat(buf, buft, sizeof buf);
966 	}
967 	strlcat(buf, "\n", sizeof buf);
968 	if (nreceived && timing) {
969 		quad_t num = nreceived + nrepeats;
970 		quad_t avg = tsum / num;
971 		quad_t dev = qsqrt(tsumsq / num - avg * avg);
972 
973 		snprintf(buft, sizeof buft, "round-trip min/avg/max/std-dev = "
974 		    "%d.%03d/%d.%03d/%d.%03d/%d.%03d ms\n",
975 		    (int)(tmin / 1000), (int)(tmin % 1000),
976 		    (int)(avg  / 1000), (int)(avg  % 1000),
977 		    (int)(tmax / 1000), (int)(tmax % 1000),
978 		    (int)(dev  / 1000), (int)(dev  % 1000));
979 		strlcat(buf, buft, sizeof buf);
980 	}
981 	write(STDOUT_FILENO, buf, strlen(buf));		/* XXX atomicio? */
982 }
983 
984 quad_t
985 qsqrt(quad_t qdev)
986 {
987 	quad_t y, x = 1;
988 
989 	if (!qdev)
990 		return(0);
991 
992 	do { /* newton was a stinker */
993 		y = x;
994 		x = qdev / x;
995 		x += y;
996 		x /= 2;
997 	} while ((x - y) > 1 || (x - y) < -1);
998 
999 	return(x);
1000 }
1001 
1002 /*
1003  * finish --
1004  *	Print out statistics, and give up.
1005  */
1006 void
1007 finish(int signo)
1008 {
1009 	(void)signal(SIGINT, SIG_IGN);
1010 
1011 	summary(1, signo);
1012 	if (signo)
1013 		_exit(nreceived ? 0 : 1);
1014 	else
1015 		exit(nreceived ? 0 : 1);
1016 }
1017 
1018 #ifdef notdef
1019 static char *ttab[] = {
1020 	"Echo Reply",		/* ip + seq + udata */
1021 	"Dest Unreachable",	/* net, host, proto, port, frag, sr + IP */
1022 	"Source Quench",	/* IP */
1023 	"Redirect",		/* redirect type, gateway, + IP  */
1024 	"Echo",
1025 	"Time Exceeded",	/* transit, frag reassem + IP */
1026 	"Parameter Problem",	/* pointer + IP */
1027 	"Timestamp",		/* id + seq + three timestamps */
1028 	"Timestamp Reply",	/* " */
1029 	"Info Request",		/* id + sq */
1030 	"Info Reply"		/* " */
1031 };
1032 #endif
1033 
1034 /*
1035  * pr_icmph --
1036  *	Print a descriptive string about an ICMP header.
1037  */
1038 void
1039 pr_icmph(struct icmp *icp)
1040 {
1041 	switch(icp->icmp_type) {
1042 	case ICMP_ECHOREPLY:
1043 		(void)printf("Echo Reply\n");
1044 		/* XXX ID + Seq + Data */
1045 		break;
1046 	case ICMP_UNREACH:
1047 		switch(icp->icmp_code) {
1048 		case ICMP_UNREACH_NET:
1049 			(void)printf("Destination Net Unreachable\n");
1050 			break;
1051 		case ICMP_UNREACH_HOST:
1052 			(void)printf("Destination Host Unreachable\n");
1053 			break;
1054 		case ICMP_UNREACH_PROTOCOL:
1055 			(void)printf("Destination Protocol Unreachable\n");
1056 			break;
1057 		case ICMP_UNREACH_PORT:
1058 			(void)printf("Destination Port Unreachable\n");
1059 			break;
1060 		case ICMP_UNREACH_NEEDFRAG:
1061 			if (icp->icmp_nextmtu != 0)
1062 				(void)printf("frag needed and DF set (MTU %d)\n",
1063 				    ntohs(icp->icmp_nextmtu));
1064 			else
1065 				(void)printf("frag needed and DF set\n");
1066 			break;
1067 		case ICMP_UNREACH_SRCFAIL:
1068 			(void)printf("Source Route Failed\n");
1069 			break;
1070 		case ICMP_UNREACH_NET_UNKNOWN:
1071 			(void)printf("Network Unknown\n");
1072 			break;
1073 		case ICMP_UNREACH_HOST_UNKNOWN:
1074 			(void)printf("Host Unknown\n");
1075 			break;
1076 		case ICMP_UNREACH_ISOLATED:
1077 			(void)printf("Source Isolated\n");
1078 			break;
1079 		case ICMP_UNREACH_NET_PROHIB:
1080 			(void)printf("Dest. Net Administratively Prohibited\n");
1081 			break;
1082 		case ICMP_UNREACH_HOST_PROHIB:
1083 			(void)printf("Dest. Host Administratively Prohibited\n");
1084 			break;
1085 		case ICMP_UNREACH_TOSNET:
1086 			(void)printf("Destination Net Unreachable for TOS\n");
1087 			break;
1088 		case ICMP_UNREACH_TOSHOST:
1089 			(void)printf("Destination Host Unreachable for TOS\n");
1090 			break;
1091 		case ICMP_UNREACH_FILTER_PROHIB:
1092 			(void)printf("Route administratively prohibited\n");
1093 			break;
1094 		case ICMP_UNREACH_HOST_PRECEDENCE:
1095 			(void)printf("Host Precedence Violation\n");
1096 			break;
1097 		case ICMP_UNREACH_PRECEDENCE_CUTOFF:
1098 			(void)printf("Precedence Cutoff\n");
1099 			break;
1100 		default:
1101 			(void)printf("Dest Unreachable, Unknown Code: %d\n",
1102 			    icp->icmp_code);
1103 			break;
1104 		}
1105 		/* Print returned IP header information */
1106 #ifndef icmp_data
1107 		pr_retip(&icp->icmp_ip);
1108 #else
1109 		pr_retip((struct ip *)icp->icmp_data);
1110 #endif
1111 		break;
1112 	case ICMP_SOURCEQUENCH:
1113 		(void)printf("Source Quench\n");
1114 #ifndef icmp_data
1115 		pr_retip(&icp->icmp_ip);
1116 #else
1117 		pr_retip((struct ip *)icp->icmp_data);
1118 #endif
1119 		break;
1120 	case ICMP_REDIRECT:
1121 		switch(icp->icmp_code) {
1122 		case ICMP_REDIRECT_NET:
1123 			(void)printf("Redirect Network");
1124 			break;
1125 		case ICMP_REDIRECT_HOST:
1126 			(void)printf("Redirect Host");
1127 			break;
1128 		case ICMP_REDIRECT_TOSNET:
1129 			(void)printf("Redirect Type of Service and Network");
1130 			break;
1131 		case ICMP_REDIRECT_TOSHOST:
1132 			(void)printf("Redirect Type of Service and Host");
1133 			break;
1134 		default:
1135 			(void)printf("Redirect, Unknown Code: %d", icp->icmp_code);
1136 			break;
1137 		}
1138 		(void)printf("(New addr: %s)\n",
1139 		    inet_ntoa(icp->icmp_gwaddr));
1140 #ifndef icmp_data
1141 		pr_retip(&icp->icmp_ip);
1142 #else
1143 		pr_retip((struct ip *)icp->icmp_data);
1144 #endif
1145 		break;
1146 	case ICMP_ECHO:
1147 		(void)printf("Echo Request\n");
1148 		/* XXX ID + Seq + Data */
1149 		break;
1150 	case ICMP_ROUTERADVERT:
1151 		/* RFC1256 */
1152 		(void)printf("Router Discovery Advertisement\n");
1153 		(void)printf("(%d entries, lifetime %d seconds)\n",
1154 		    icp->icmp_num_addrs, ntohs(icp->icmp_lifetime));
1155 		break;
1156 	case ICMP_ROUTERSOLICIT:
1157 		/* RFC1256 */
1158 		(void)printf("Router Discovery Solicitation\n");
1159 		break;
1160 	case ICMP_TIMXCEED:
1161 		switch(icp->icmp_code) {
1162 		case ICMP_TIMXCEED_INTRANS:
1163 			(void)printf("Time to live exceeded\n");
1164 			break;
1165 		case ICMP_TIMXCEED_REASS:
1166 			(void)printf("Frag reassembly time exceeded\n");
1167 			break;
1168 		default:
1169 			(void)printf("Time exceeded, Unknown Code: %d\n",
1170 			    icp->icmp_code);
1171 			break;
1172 		}
1173 #ifndef icmp_data
1174 		pr_retip(&icp->icmp_ip);
1175 #else
1176 		pr_retip((struct ip *)icp->icmp_data);
1177 #endif
1178 		break;
1179 	case ICMP_PARAMPROB:
1180 		switch(icp->icmp_code) {
1181 		case ICMP_PARAMPROB_OPTABSENT:
1182 			(void)printf("Parameter problem, required option "
1183 			    "absent: pointer = 0x%02x\n",
1184 			    ntohs(icp->icmp_hun.ih_pptr));
1185 			break;
1186 		default:
1187 			(void)printf("Parameter problem: pointer = 0x%02x\n",
1188 			    ntohs(icp->icmp_hun.ih_pptr));
1189 			break;
1190 		}
1191 #ifndef icmp_data
1192 		pr_retip(&icp->icmp_ip);
1193 #else
1194 		pr_retip((struct ip *)icp->icmp_data);
1195 #endif
1196 		break;
1197 	case ICMP_TSTAMP:
1198 		(void)printf("Timestamp\n");
1199 		/* XXX ID + Seq + 3 timestamps */
1200 		break;
1201 	case ICMP_TSTAMPREPLY:
1202 		(void)printf("Timestamp Reply\n");
1203 		/* XXX ID + Seq + 3 timestamps */
1204 		break;
1205 	case ICMP_IREQ:
1206 		(void)printf("Information Request\n");
1207 		/* XXX ID + Seq */
1208 		break;
1209 	case ICMP_IREQREPLY:
1210 		(void)printf("Information Reply\n");
1211 		/* XXX ID + Seq */
1212 		break;
1213 #ifdef ICMP_MASKREQ
1214 	case ICMP_MASKREQ:
1215 		(void)printf("Address Mask Request\n");
1216 		break;
1217 #endif
1218 #ifdef ICMP_MASKREPLY
1219 	case ICMP_MASKREPLY:
1220 		(void)printf("Address Mask Reply (Mask 0x%08x)\n",
1221 		    ntohl(icp->icmp_mask));
1222 		break;
1223 #endif
1224 	default:
1225 		(void)printf("Unknown ICMP type: %d\n", icp->icmp_type);
1226 	}
1227 }
1228 
1229 /*
1230  * pr_iph --
1231  *	Print an IP header with options.
1232  */
1233 void
1234 pr_iph(struct ip *ip)
1235 {
1236 	int hlen;
1237 	u_char *cp;
1238 
1239 	hlen = ip->ip_hl << 2;
1240 	cp = (u_char *)ip + 20;		/* point to options */
1241 
1242 	(void)printf("Vr HL TOS  Len   ID Flg  off TTL Pro  cks      Src      Dst Data\n");
1243 	(void)printf(" %1x  %1x  %02x %04x %04x",
1244 	    ip->ip_v, ip->ip_hl, ip->ip_tos, ip->ip_len, ip->ip_id);
1245 	(void)printf("   %1x %04x", ((ip->ip_off) & 0xe000) >> 13,
1246 	    (ip->ip_off) & 0x1fff);
1247 	(void)printf("  %02x  %02x %04x", ip->ip_ttl, ip->ip_p, ip->ip_sum);
1248 	(void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_src.s_addr));
1249 	(void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_dst.s_addr));
1250 	/* dump and option bytes */
1251 	while (hlen-- > 20) {
1252 		(void)printf("%02x", *cp++);
1253 	}
1254 	(void)putchar('\n');
1255 }
1256 
1257 /*
1258  * pr_addr --
1259  *	Return an ascii host address as a dotted quad and optionally with
1260  * a hostname.
1261  */
1262 char *
1263 pr_addr(in_addr_t a)
1264 {
1265 	struct hostent *hp;
1266 	struct in_addr in;
1267 	static char buf[16+3+MAXHOSTNAMELEN];
1268 
1269 	in.s_addr = a;
1270 	if ((options & F_NUMERIC) ||
1271 	    !(hp = gethostbyaddr((char *)&in.s_addr, sizeof(in.s_addr), AF_INET)))
1272 		(void)snprintf(buf, sizeof buf, "%s", inet_ntoa(in));
1273 	else
1274 		(void)snprintf(buf, sizeof buf, "%s (%s)", hp->h_name,
1275 		    inet_ntoa(in));
1276 	return(buf);
1277 }
1278 
1279 /*
1280  * pr_retip --
1281  *	Dump some info on a returned (via ICMP) IP packet.
1282  */
1283 void
1284 pr_retip(struct ip *ip)
1285 {
1286 	int hlen;
1287 	u_char *cp;
1288 
1289 	pr_iph(ip);
1290 	hlen = ip->ip_hl << 2;
1291 	cp = (u_char *)ip + hlen;
1292 
1293 	if (ip->ip_p == 6)
1294 		(void)printf("TCP: from port %u, to port %u (decimal)\n",
1295 		    (*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3)));
1296 	else if (ip->ip_p == 17)
1297 		(void)printf("UDP: from port %u, to port %u (decimal)\n",
1298 		    (*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3)));
1299 }
1300 
1301 void
1302 fill(char *bp, char *patp)
1303 {
1304 	int ii, jj, kk;
1305 	int pat[16];
1306 	char *cp;
1307 
1308 	for (cp = patp; *cp; cp++)
1309 		if (!isxdigit(*cp))
1310 			errx(1, "patterns must be specified as hex digits");
1311 	ii = sscanf(patp,
1312 	    "%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x",
1313 	    &pat[0], &pat[1], &pat[2], &pat[3], &pat[4], &pat[5], &pat[6],
1314 	    &pat[7], &pat[8], &pat[9], &pat[10], &pat[11], &pat[12],
1315 	    &pat[13], &pat[14], &pat[15]);
1316 
1317 	if (ii > 0)
1318 		for (kk = 0;
1319 		    kk <= MAXPAYLOAD - (8 + sizeof(struct tvi) + ii);
1320 		    kk += ii)
1321 			for (jj = 0; jj < ii; ++jj)
1322 				bp[jj + kk] = pat[jj];
1323 	if (!(options & F_QUIET)) {
1324 		(void)printf("PATTERN: 0x");
1325 		for (jj = 0; jj < ii; ++jj)
1326 			(void)printf("%02x", bp[jj] & 0xFF);
1327 		(void)printf("\n");
1328 	}
1329 }
1330 
1331 /*
1332  * when we get types of ICMP message with parts of the orig. datagram
1333  * we want to try to assure ourselves that it is from this instance
1334  * of ping, and not say, a refused finger connection or something
1335  */
1336 int
1337 check_icmph(struct ip *iph)
1338 {
1339 	struct icmp *icmph;
1340 
1341 	/* only allow IP version 4 */
1342 	if (iph->ip_v != 4)
1343 		return 0;
1344 
1345 	/* Only allow ICMP */
1346 	if (iph->ip_p != IPPROTO_ICMP)
1347 		return 0;
1348 
1349 	icmph = (struct icmp *) (iph + (4 * iph->ip_hl));
1350 
1351 	/* make sure it is in response to an ECHO request */
1352 	if (icmph->icmp_type != 8)
1353 		return 0;
1354 
1355 	/* ok, make sure it has the right id on it */
1356 	if (icmph->icmp_hun.ih_idseq.icd_id != ident)
1357 		return 0;
1358 
1359 	return 1;
1360 }
1361 
1362 void
1363 usage(void)
1364 {
1365 	(void)fprintf(stderr,
1366 	    "usage: ping [-DdEefLnqRrv] [-c count] [-I ifaddr] [-i wait]\n"
1367 	    "\t[-l preload] [-p pattern] [-s packetsize] [-T tos] [-t ttl]\n"
1368 	    "\t[-V rtable] [-w maxwait] host\n");
1369 	exit(1);
1370 }
1371