ping.c revision 1.47 1 /* $NetBSD: ping.c,v 1.47 1999/03/08 01:16:20 sommerfe Exp $ */
2
3 /*
4 * Copyright (c) 1989, 1993
5 * The Regents of the University of California. All rights reserved.
6 *
7 * This code is derived from software contributed to Berkeley by
8 * Mike Muuss.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. All advertising materials mentioning features or use of this software
19 * must display the following acknowledgement:
20 * This product includes software developed by the University of
21 * California, Berkeley and its contributors.
22 * 4. Neither the name of the University nor the names of its contributors
23 * may be used to endorse or promote products derived from this software
24 * without specific prior written permission.
25 *
26 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * SUCH DAMAGE.
37 */
38
39 /*
40 * P I N G . C
41 *
42 * Using the InterNet Control Message Protocol (ICMP) "ECHO" facility,
43 * measure round-trip-delays and packet loss across network paths.
44 *
45 * Author -
46 * Mike Muuss
47 * U. S. Army Ballistic Research Laboratory
48 * December, 1983
49 * Modified at Uc Berkeley
50 * Record Route and verbose headers - Phil Dykstra, BRL, March 1988.
51 * Multicast options (ttl, if, loop) - Steve Deering, Stanford, August 1988.
52 * ttl, duplicate detection - Cliff Frost, UCB, April 1989
53 * Pad pattern - Cliff Frost (from Tom Ferrin, UCSF), April 1989
54 *
55 * Status -
56 * Public Domain. Distribution Unlimited.
57 *
58 * Bugs -
59 * More statistics could always be gathered.
60 * This program has to run SUID to ROOT to access the ICMP socket.
61 */
62
63 #include <sys/cdefs.h>
64 #ifndef lint
65 __RCSID("$NetBSD: ping.c,v 1.47 1999/03/08 01:16:20 sommerfe Exp $");
66 #endif
67
68 #include <stdio.h>
69 #include <errno.h>
70 #include <sys/time.h>
71 #include <sys/types.h>
72 #include <sys/signal.h>
73 #include <sys/param.h>
74 #include <sys/socket.h>
75 #include <sys/file.h>
76 #include <termios.h>
77 #include <stdlib.h>
78 #include <unistd.h>
79 #include <limits.h>
80 #include <math.h>
81 #include <string.h>
82 #include <err.h>
83 #ifdef sgi
84 #include <bstring.h>
85 #include <getopt.h>
86 #include <sys/prctl.h>
87 #ifndef PRE_KUDZU
88 #include <cap_net.h>
89 #else
90 #define cap_socket socket
91 #endif
92 #else
93 #define cap_socket socket
94 #include <err.h>
95 #endif
96
97 #include <netinet/in_systm.h>
98 #include <netinet/in.h>
99 #include <netinet/ip.h>
100 #include <netinet/ip_icmp.h>
101 #include <netinet/ip_var.h>
102 #include <arpa/inet.h>
103 #include <ctype.h>
104 #include <netdb.h>
105
106 #define FLOOD_INTVL 0.01 /* default flood output interval */
107 #define MAXPACKET (65536-60-8) /* max packet size */
108
109 #define F_VERBOSE 0x0001
110 #define F_QUIET 0x0002 /* minimize all output */
111 #define F_SEMI_QUIET 0x0004 /* ignore our ICMP errors */
112 #define F_FLOOD 0x0008 /* flood-ping */
113 #define F_RECORD_ROUTE 0x0010 /* record route */
114 #define F_SOURCE_ROUTE 0x0020 /* loose source route */
115 #define F_PING_FILLED 0x0040 /* is buffer filled with user data? */
116 #define F_PING_RANDOM 0x0080 /* use random data */
117 #define F_NUMERIC 0x0100 /* do not do gethostbyaddr() calls */
118 #define F_TIMING 0x0200 /* room for a timestamp */
119 #define F_DF 0x0400 /* set IP DF bit */
120 #define F_SOURCE_ADDR 0x0800 /* set source IP address/interface */
121 #define F_ONCE 0x1000 /* exit(0) after receiving 1 reply */
122 #define F_MCAST 0x2000 /* multicast target */
123 #define F_MCAST_NOLOOP 0x4000 /* no multicast loopback */
124
125
126 /* MAX_DUP_CHK is the number of bits in received table, the
127 * maximum number of received sequence numbers we can track to check
128 * for duplicates.
129 */
130 #define MAX_DUP_CHK (8 * 2048)
131 u_char rcvd_tbl[MAX_DUP_CHK/8];
132 int nrepeats = 0;
133 #define A(seq) rcvd_tbl[(seq/8)%sizeof(rcvd_tbl)] /* byte in array */
134 #define B(seq) (1 << (seq & 0x07)) /* bit in byte */
135 #define SET(seq) (A(seq) |= B(seq))
136 #define CLR(seq) (A(seq) &= (~B(seq)))
137 #define TST(seq) (A(seq) & B(seq))
138
139
140
141 u_char *packet;
142 int packlen;
143 int pingflags = 0, options;
144 char *fill_pat;
145
146 int s; /* Socket file descriptor */
147
148 #define PHDR_LEN sizeof(struct timeval) /* size of timestamp header */
149 struct sockaddr_in whereto, send_addr; /* Who to ping */
150 struct sockaddr_in src_addr; /* from where */
151 struct sockaddr_in loc_addr; /* 127.1 */
152 int datalen = 64-PHDR_LEN; /* How much data */
153
154 #ifdef sgi
155 static char *__progname;
156 #else
157 extern char *__progname;
158 #endif
159
160
161 char hostname[MAXHOSTNAMELEN];
162
163 static struct {
164 struct ip o_ip;
165 char o_opt[MAX_IPOPTLEN];
166 union {
167 u_char u_buf[MAXPACKET];
168 struct icmp u_icmp;
169 } o_u;
170 } out_pack;
171 #define opack_icmp out_pack.o_u.u_icmp
172 struct ip *opack_ip;
173
174 char optspace[MAX_IPOPTLEN]; /* record route space */
175 int optlen;
176
177
178 int npackets; /* total packets to send */
179 int preload; /* number of packets to "preload" */
180 int ntransmitted; /* output sequence # = #sent */
181 int ident; /* our ID, in network byte order */
182
183 int nreceived; /* # of packets we got back */
184
185 double interval; /* interval between packets */
186 struct timeval interval_tv;
187 double tmin = 999999999.0;
188 double tmax = 0.0;
189 double tsum = 0.0; /* sum of all times */
190 double tsumsq = 0.0;
191 double maxwait = 0.0;
192
193 #ifdef SIGINFO
194 int reset_kerninfo;
195 #endif
196
197 int bufspace = 60*1024;
198
199 struct timeval now, clear_cache, last_tx, next_tx, first_tx;
200 struct timeval last_rx, first_rx;
201 int lastrcvd = 1; /* last ping sent has been received */
202
203 static struct timeval jiggle_time;
204 static int jiggle_cnt, total_jiggled, jiggle_direction = -1;
205
206 static void doit(void);
207 static void prefinish(int);
208 static void prtsig(int);
209 static void finish(int);
210 static void summary(int);
211 static void pinger(void);
212 static void fill(void);
213 static void rnd_fill(void);
214 static double diffsec(struct timeval *, struct timeval *);
215 static void timevaladd(struct timeval *, struct timeval *);
216 static void sec_to_timeval(const double, struct timeval *);
217 static double timeval_to_sec(const struct timeval *);
218 static void pr_pack(u_char *, int, struct sockaddr_in *);
219 static u_short in_cksum(u_short *, u_int);
220 static void pr_saddr(char *, u_char *);
221 static char *pr_addr(struct in_addr *);
222 static void pr_iph(struct icmp *, int);
223 static void pr_retip(struct icmp *, int);
224 static int pr_icmph(struct icmp *, struct sockaddr_in *, int);
225 static void jiggle(int), jiggle_flush(int);
226 static void gethost(const char *, const char *,
227 struct sockaddr_in *, char *, int);
228 static void usage(void);
229
230
231 int
232 main(int argc, char *argv[])
233 {
234 int c, i, on = 1, hostind = 0;
235 long l;
236 u_char ttl = 0;
237 u_long tos = 0;
238 char *p;
239 #ifdef SIGINFO
240 struct termios ts;
241 #endif
242
243
244 #if defined(SIGINFO) && defined(NOKERNINFO)
245 if (tcgetattr (0, &ts) != -1) {
246 reset_kerninfo = !(ts.c_lflag & NOKERNINFO);
247 ts.c_lflag |= NOKERNINFO;
248 tcsetattr (0, TCSANOW, &ts);
249 }
250 #endif
251 #ifdef sgi
252 __progname = argv[0];
253 #endif
254 while ((c = getopt(argc, argv,
255 "c:dDfg:h:i:I:l:Lnop:PqQrRs:t:T:vw:")) != -1) {
256 switch (c) {
257 case 'c':
258 npackets = strtol(optarg, &p, 0);
259 if (*p != '\0' || npackets <= 0)
260 errx(1, "Bad/invalid number of packets");
261 break;
262 case 'D':
263 pingflags |= F_DF;
264 break;
265 case 'd':
266 options |= SO_DEBUG;
267 break;
268 case 'f':
269 pingflags |= F_FLOOD;
270 break;
271 case 'h':
272 hostind = optind-1;
273 break;
274 case 'i': /* wait between sending packets */
275 interval = strtod(optarg, &p);
276 if (*p != '\0' || interval <= 0)
277 errx(1, "Bad/invalid interval %s", optarg);
278 break;
279 case 'l':
280 preload = strtol(optarg, &p, 0);
281 if (*p != '\0' || preload < 0)
282 errx(1, "Bad/invalid preload value %s",
283 optarg);
284 break;
285 case 'n':
286 pingflags |= F_NUMERIC;
287 break;
288 case 'o':
289 pingflags |= F_ONCE;
290 break;
291 case 'p': /* fill buffer with user pattern */
292 if (pingflags & F_PING_RANDOM)
293 errx(1, "Only one of -P and -p allowed");
294 pingflags |= F_PING_FILLED;
295 fill_pat = optarg;
296 break;
297 case 'P':
298 if (pingflags & F_PING_FILLED)
299 errx(1, "Only one of -P and -p allowed");
300 pingflags |= F_PING_RANDOM;
301 break;
302 case 'q':
303 pingflags |= F_QUIET;
304 break;
305 case 'Q':
306 pingflags |= F_SEMI_QUIET;
307 break;
308 case 'r':
309 options |= SO_DONTROUTE;
310 break;
311 case 's': /* size of packet to send */
312 datalen = strtol(optarg, &p, 0);
313 if (*p != '\0' || datalen <= 0)
314 errx(1, "Bad/invalid packet size %s", optarg);
315 if (datalen > MAXPACKET)
316 errx(1, "packet size is too large");
317 break;
318 case 'v':
319 pingflags |= F_VERBOSE;
320 break;
321 case 'R':
322 pingflags |= F_RECORD_ROUTE;
323 break;
324 case 'L':
325 pingflags |= F_MCAST_NOLOOP;
326 break;
327 case 't':
328 tos = strtoul(optarg, &p, 0);
329 if (*p != '\0' || tos > 0xFF)
330 errx(1, "bad tos value: %s", optarg);
331 break;
332 case 'T':
333 l = strtol(optarg, &p, 0);
334 if (*p != '\0' || l > 255 || l <= 0)
335 errx(1, "ttl out of range");
336 ttl = (u_char)l; /* cannot check >255 otherwise */
337 break;
338 case 'I':
339 pingflags |= F_SOURCE_ADDR;
340 gethost("-I", optarg, &src_addr, 0, 0);
341 break;
342 case 'g':
343 pingflags |= F_SOURCE_ROUTE;
344 gethost("-g", optarg, &send_addr, 0, 0);
345 break;
346 case 'w':
347 maxwait = strtod(optarg, &p);
348 if (*p != '\0' || maxwait <= 0)
349 errx(1, "Bad/invalid maxwait time %s", optarg);
350 break;
351 default:
352 usage();
353 break;
354 }
355 }
356
357 if (interval == 0)
358 interval = (pingflags & F_FLOOD) ? FLOOD_INTVL : 1.0;
359 #ifndef sgi
360 if (pingflags & F_FLOOD && getuid())
361 errx(1, "Must be superuser to use -f");
362 if (interval < 1.0 && getuid())
363 errx(1, "Must be superuser to use < 1 sec ping interval");
364 if (preload > 0 && getuid())
365 errx(1, "Must be superuser to use -l");
366 #endif
367 sec_to_timeval(interval, &interval_tv);
368
369 if (npackets != 0) {
370 npackets += preload;
371 } else {
372 npackets = INT_MAX;
373 }
374
375 if (hostind == 0) {
376 if (optind != argc-1)
377 usage();
378 else
379 hostind = optind;
380 }
381 else if (hostind >= argc - 1)
382 usage();
383
384 gethost("", argv[hostind], &whereto, hostname, sizeof(hostname));
385 if (IN_MULTICAST(ntohl(whereto.sin_addr.s_addr)))
386 pingflags |= F_MCAST;
387 if (!(pingflags & F_SOURCE_ROUTE))
388 (void) memcpy(&send_addr, &whereto, sizeof(send_addr));
389
390 loc_addr.sin_family = AF_INET;
391 loc_addr.sin_addr.s_addr = htonl((127<<24)+1);
392
393 if (datalen >= PHDR_LEN) /* can we time them? */
394 pingflags |= F_TIMING;
395 packlen = datalen + 60 + 76; /* MAXIP + MAXICMP */
396 if ((packet = (u_char *)malloc(packlen)) == NULL)
397 err(1, "Out of memory");
398
399 if (pingflags & F_PING_FILLED) {
400 fill();
401 } else if (pingflags & F_PING_RANDOM) {
402 rnd_fill();
403 } else {
404 for (i = PHDR_LEN; i < datalen; i++)
405 opack_icmp.icmp_data[i] = i;
406 }
407
408 ident = htons(getpid()) & 0xFFFF;
409
410 if ((s = cap_socket(AF_INET, SOCK_RAW, IPPROTO_ICMP)) < 0)
411 err(1, "Cannot create socket");
412 if (options & SO_DEBUG) {
413 if (setsockopt(s, SOL_SOCKET, SO_DEBUG,
414 (char *)&on, sizeof(on)) == -1)
415 warn("Can't turn on socket debugging");
416 }
417 if (options & SO_DONTROUTE) {
418 if (setsockopt(s, SOL_SOCKET, SO_DONTROUTE,
419 (char *)&on, sizeof(on)) == -1)
420 warn("SO_DONTROUTE");
421 }
422
423 if (pingflags & F_SOURCE_ROUTE) {
424 optspace[IPOPT_OPTVAL] = IPOPT_LSRR;
425 optspace[IPOPT_OLEN] = optlen = 7;
426 optspace[IPOPT_OFFSET] = IPOPT_MINOFF;
427 (void)memcpy(&optspace[IPOPT_MINOFF-1], &whereto.sin_addr,
428 sizeof(whereto.sin_addr));
429 optspace[optlen++] = IPOPT_NOP;
430 }
431 if (pingflags & F_RECORD_ROUTE) {
432 optspace[optlen+IPOPT_OPTVAL] = IPOPT_RR;
433 optspace[optlen+IPOPT_OLEN] = (MAX_IPOPTLEN -1-optlen);
434 optspace[optlen+IPOPT_OFFSET] = IPOPT_MINOFF;
435 optlen = MAX_IPOPTLEN;
436 }
437 /* this leaves opack_ip 0(mod 4) aligned */
438 opack_ip = (struct ip *)((char *)&out_pack.o_ip
439 + sizeof(out_pack.o_opt)
440 - optlen);
441 (void) memcpy(opack_ip + 1, optspace, optlen);
442
443 if (setsockopt(s,IPPROTO_IP,IP_HDRINCL, (char *) &on, sizeof(on)) < 0)
444 err(1, "Can't set special IP header");
445
446 opack_ip->ip_v = IPVERSION;
447 opack_ip->ip_hl = (sizeof(struct ip)+optlen) >> 2;
448 opack_ip->ip_tos = tos;
449 opack_ip->ip_off = (pingflags & F_DF) ? IP_DF : 0;
450 opack_ip->ip_ttl = ttl ? ttl : MAXTTL;
451 opack_ip->ip_p = IPPROTO_ICMP;
452 opack_ip->ip_src = src_addr.sin_addr;
453 opack_ip->ip_dst = send_addr.sin_addr;
454
455 if (pingflags & F_MCAST) {
456 if (pingflags & F_MCAST_NOLOOP) {
457 u_char loop = 0;
458 if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_LOOP,
459 (char *) &loop, 1) < 0)
460 err(1, "Can't disable multicast loopback");
461 }
462
463 if (ttl != 0
464 && setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL,
465 (char *) &ttl, 1) < 0)
466 err(1, "Can't set multicast time-to-live");
467
468 if ((pingflags & F_SOURCE_ADDR)
469 && setsockopt(s, IPPROTO_IP, IP_MULTICAST_IF,
470 (char *) &src_addr.sin_addr,
471 sizeof(src_addr.sin_addr)) < 0)
472 err(1, "Can't set multicast source interface");
473
474 } else if (pingflags & F_SOURCE_ADDR) {
475 if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_IF,
476 (char *) &src_addr.sin_addr,
477 sizeof(src_addr.sin_addr)) < 0)
478 err(1, "Can't set source interface/address");
479 }
480
481 (void)printf("PING %s (%s): %d data bytes\n", hostname,
482 inet_ntoa(whereto.sin_addr), datalen);
483
484 /* When pinging the broadcast address, you can get a lot
485 * of answers. Doing something so evil is useful if you
486 * are trying to stress the ethernet, or just want to
487 * fill the arp cache to get some stuff for /etc/ethers.
488 */
489 while (0 > setsockopt(s, SOL_SOCKET, SO_RCVBUF,
490 (char*)&bufspace, sizeof(bufspace))) {
491 if ((bufspace -= 4096) == 0)
492 err(1, "Cannot set the receive buffer size");
493 }
494
495 /* make it possible to send giant probes, but do not worry now
496 * if it fails, since we probably won't send giant probes.
497 */
498 (void)setsockopt(s, SOL_SOCKET, SO_SNDBUF,
499 (char*)&bufspace, sizeof(bufspace));
500
501 (void)signal(SIGINT, prefinish);
502 #ifdef SIGINFO
503 (void)signal(SIGINFO, prtsig);
504 #else
505 (void)signal(SIGQUIT, prtsig);
506 #endif
507 (void)signal(SIGCONT, prtsig);
508
509 /* fire off them quickies */
510 for (i = 0; i < preload; i++) {
511 (void)gettimeofday(&now, 0);
512 pinger();
513 }
514
515 doit();
516 return 0;
517 }
518
519
520 static void
521 doit(void)
522 {
523 int cc;
524 struct sockaddr_in from;
525 int fromlen;
526 double sec, last, d_last;
527 struct timeval timeout;
528 fd_set fdmask;
529
530
531 (void)gettimeofday(&clear_cache,0);
532 if (maxwait != 0) {
533 last = timeval_to_sec(&clear_cache) + maxwait;
534 d_last = 0;
535 } else {
536 last = 0;
537 d_last = 365*24*60*60;
538 }
539
540 FD_ZERO(&fdmask);
541 do {
542 (void)gettimeofday(&now,0);
543
544 if (last != 0)
545 d_last = last - timeval_to_sec(&now);
546
547 if (ntransmitted < npackets && d_last > 0) {
548 /* send if within 100 usec or late for next packet */
549 sec = diffsec(&next_tx,&now);
550 if (sec <= 0.0001
551 || (lastrcvd && (pingflags & F_FLOOD))) {
552 pinger();
553 sec = diffsec(&next_tx,&now);
554 }
555 if (sec < 0.0)
556 sec = 0.0;
557 if (d_last < sec)
558 sec = d_last;
559
560 } else {
561 /* For the last response, wait twice as long as the
562 * worst case seen, or 10 times as long as the
563 * maximum interpacket interval, whichever is longer.
564 */
565 sec = MAX(2*tmax,10*interval) - diffsec(&now,&last_tx);
566 if (d_last < sec)
567 sec = d_last;
568 if (sec <= 0)
569 break;
570 }
571
572
573 sec_to_timeval(sec, &timeout);
574
575 FD_SET(s, &fdmask);
576 cc = select(s+1, &fdmask, 0, 0, &timeout);
577 if (cc <= 0) {
578 if (cc < 0) {
579 if (errno == EINTR)
580 continue;
581 jiggle_flush(1);
582 err(1, "select");
583 }
584 continue;
585 }
586
587 fromlen = sizeof(from);
588 cc = recvfrom(s, (char *) packet, packlen,
589 0, (struct sockaddr *)&from,
590 &fromlen);
591 if (cc < 0) {
592 if (errno != EINTR) {
593 jiggle_flush(1);
594 warn("recvfrom");
595 (void)fflush(stderr);
596 }
597 continue;
598 }
599 (void)gettimeofday(&now, 0);
600 pr_pack(packet, cc, &from);
601
602 } while (nreceived < npackets
603 && (nreceived == 0 || !(pingflags & F_ONCE)));
604
605 finish(0);
606 }
607
608
609 static void
610 jiggle_flush(int nl) /* new line if there are dots */
611 {
612 int serrno = errno;
613
614 if (jiggle_cnt > 0) {
615 total_jiggled += jiggle_cnt;
616 jiggle_direction = 1;
617 do {
618 (void)putchar('.');
619 } while (--jiggle_cnt > 0);
620
621 } else if (jiggle_cnt < 0) {
622 total_jiggled -= jiggle_cnt;
623 jiggle_direction = -1;
624 do {
625 (void)putchar('\b');
626 } while (++jiggle_cnt < 0);
627 }
628
629 if (nl) {
630 if (total_jiggled != 0)
631 (void)putchar('\n');
632 total_jiggled = 0;
633 jiggle_direction = -1;
634 }
635
636 (void)fflush(stdout);
637 (void)fflush(stderr);
638 jiggle_time = now;
639 errno = serrno;
640 }
641
642
643 /* jiggle the cursor for flood-ping
644 */
645 static void
646 jiggle(int delta)
647 {
648 double dt;
649
650 if (pingflags & F_QUIET)
651 return;
652
653 /* do not back up into messages */
654 if (total_jiggled+jiggle_cnt+delta < 0)
655 return;
656
657 jiggle_cnt += delta;
658
659 /* flush the FLOOD dots when things are quiet
660 * or occassionally to make the cursor jiggle.
661 */
662 dt = diffsec(&last_tx, &jiggle_time);
663 if (dt > 0.2 || (dt >= 0.15 && delta*jiggle_direction < 0))
664 jiggle_flush(0);
665 }
666
667
668 /*
669 * Compose and transmit an ICMP ECHO REQUEST packet. The IP packet
670 * will be added on by the kernel. The ID field is our UNIX process ID,
671 * and the sequence number is an ascending integer. The first PHDR_LEN bytes
672 * of the data portion are used to hold a UNIX "timeval" struct in VAX
673 * byte-order, to compute the round-trip time.
674 */
675 static void
676 pinger(void)
677 {
678 int i, cc, sw;
679
680 opack_icmp.icmp_code = 0;
681 opack_icmp.icmp_seq = htons((u_short)(ntransmitted));
682
683 /* clear the cached route in the kernel after an ICMP
684 * response such as a Redirect is seen to stop causing
685 * more such packets. Also clear the cached route
686 * periodically in case of routing changes that make
687 * black holes come and go.
688 */
689 if (clear_cache.tv_sec != now.tv_sec) {
690 opack_icmp.icmp_type = ICMP_ECHOREPLY;
691 opack_icmp.icmp_id = ~ident;
692 opack_icmp.icmp_cksum = 0;
693 opack_icmp.icmp_cksum = in_cksum((u_short*)&opack_icmp,
694 PHDR_LEN);
695 sw = 0;
696 if (setsockopt(s,IPPROTO_IP,IP_HDRINCL,
697 (char *)&sw,sizeof(sw)) < 0)
698 err(1, "Can't turn off special IP header");
699 if (sendto(s, (char *) &opack_icmp, PHDR_LEN, MSG_DONTROUTE,
700 (struct sockaddr *)&loc_addr,
701 sizeof(struct sockaddr_in)) < 0) {
702 /*
703 * XXX: we only report this as a warning in verbose
704 * mode because people get confused when they see
705 * this error when they are running in single user
706 * mode and they have not configured lo0
707 */
708 if (pingflags & F_VERBOSE)
709 warn("failed to clear cached route");
710 }
711 sw = 1;
712 if (setsockopt(s,IPPROTO_IP,IP_HDRINCL,
713 (char *)&sw, sizeof(sw)) < 0)
714 err(1, "Can't set special IP header");
715
716 (void)gettimeofday(&clear_cache,0);
717 }
718
719 opack_icmp.icmp_type = ICMP_ECHO;
720 opack_icmp.icmp_id = ident;
721 if (pingflags & F_TIMING)
722 (void) memcpy(&opack_icmp.icmp_data[0], &now, sizeof(now));
723 cc = datalen+PHDR_LEN;
724 opack_icmp.icmp_cksum = 0;
725 opack_icmp.icmp_cksum = in_cksum((u_short*)&opack_icmp, cc);
726
727 cc += opack_ip->ip_hl<<2;
728 opack_ip->ip_len = cc;
729 i = sendto(s, (char *) opack_ip, cc, 0,
730 (struct sockaddr *)&send_addr, sizeof(struct sockaddr_in));
731 if (i != cc) {
732 jiggle_flush(1);
733 if (i < 0)
734 warn("sendto");
735 else
736 warnx("wrote %s %d chars, ret=%d", hostname, cc, i);
737 (void)fflush(stderr);
738 }
739 lastrcvd = 0;
740
741 CLR(ntransmitted);
742 ntransmitted++;
743
744 last_tx = now;
745 if (next_tx.tv_sec == 0) {
746 first_tx = now;
747 next_tx = now;
748 }
749
750 /* Transmit regularly, at always the same microsecond in the
751 * second when going at one packet per second.
752 * If we are at most 100 ms behind, send extras to get caught up.
753 * Otherwise, skip packets we were too slow to send.
754 */
755 if (diffsec(&next_tx, &now) <= interval) {
756 do {
757 timevaladd(&next_tx, &interval_tv);
758 } while (diffsec(&next_tx, &now) < -0.1);
759 }
760
761 if (pingflags & F_FLOOD)
762 jiggle(1);
763
764 /* While the packet is going out, ready buffer for the next
765 * packet. Use a fast but not very good random number generator.
766 */
767 if (pingflags & F_PING_RANDOM)
768 rnd_fill();
769 }
770
771
772 static void
773 pr_pack_sub(int cc,
774 char *addr,
775 int seqno,
776 int dupflag,
777 int ttl,
778 double triptime)
779 {
780 jiggle_flush(1);
781
782 if (pingflags & F_FLOOD)
783 return;
784
785 (void)printf("%d bytes from %s: icmp_seq=%u", cc, addr, seqno);
786 if (dupflag)
787 (void)printf(" DUP!");
788 (void)printf(" ttl=%d", ttl);
789 if (pingflags & F_TIMING)
790 (void)printf(" time=%.3f ms", triptime*1000.0);
791 }
792
793
794 /*
795 * Print out the packet, if it came from us. This logic is necessary
796 * because ALL readers of the ICMP socket get a copy of ALL ICMP packets
797 * which arrive ('tis only fair). This permits multiple copies of this
798 * program to be run without having intermingled output (or statistics!).
799 */
800 static void
801 pr_pack(u_char *buf,
802 int tot_len,
803 struct sockaddr_in *from)
804 {
805 struct ip *ip;
806 struct icmp *icp;
807 int i, j, net_len;
808 u_char *cp;
809 static int old_rrlen;
810 static char old_rr[MAX_IPOPTLEN];
811 int hlen, dupflag = 0, dumped;
812 double triptime = 0.0;
813 #define PR_PACK_SUB() {if (!dumped) { \
814 dumped = 1; \
815 pr_pack_sub(net_len, inet_ntoa(from->sin_addr), \
816 ntohs((u_short)icp->icmp_seq), \
817 dupflag, ip->ip_ttl, triptime);}}
818
819 /* Check the IP header */
820 ip = (struct ip *) buf;
821 hlen = ip->ip_hl << 2;
822 if (tot_len < hlen + ICMP_MINLEN) {
823 if (pingflags & F_VERBOSE) {
824 jiggle_flush(1);
825 (void)printf("packet too short (%d bytes) from %s\n",
826 tot_len, inet_ntoa(from->sin_addr));
827 }
828 return;
829 }
830
831 /* Now the ICMP part */
832 dumped = 0;
833 net_len = tot_len - hlen;
834 icp = (struct icmp *)(buf + hlen);
835 if (icp->icmp_type == ICMP_ECHOREPLY
836 && icp->icmp_id == ident) {
837 if (icp->icmp_seq == htons((u_short)(ntransmitted-1)))
838 lastrcvd = 1;
839 last_rx = now;
840 if (first_rx.tv_sec == 0)
841 first_rx = last_rx;
842 nreceived++;
843 if (pingflags & F_TIMING) {
844 struct timeval tv;
845 (void) memcpy(&tv, icp->icmp_data, sizeof(tv));
846 triptime = diffsec(&last_rx, &tv);
847 tsum += triptime;
848 tsumsq += triptime * triptime;
849 if (triptime < tmin)
850 tmin = triptime;
851 if (triptime > tmax)
852 tmax = triptime;
853 }
854
855 if (TST(ntohs((u_short)icp->icmp_seq))) {
856 nrepeats++, nreceived--;
857 dupflag=1;
858 } else {
859 SET(ntohs((u_short)icp->icmp_seq));
860 }
861
862 if (tot_len != opack_ip->ip_len) {
863 PR_PACK_SUB();
864 (void)printf("\nwrong total length %d instead of %d",
865 tot_len, opack_ip->ip_len);
866 }
867
868 if (pingflags & F_QUIET)
869 return;
870
871 if (!(pingflags & F_FLOOD))
872 PR_PACK_SUB();
873
874 /* check the data */
875 if (datalen > PHDR_LEN
876 && !(pingflags & F_PING_RANDOM)
877 && memcmp(&icp->icmp_data[PHDR_LEN],
878 &opack_icmp.icmp_data[PHDR_LEN],
879 datalen-PHDR_LEN)) {
880 for (i=PHDR_LEN; i<datalen; i++) {
881 if (icp->icmp_data[PHDR_LEN+i]
882 != opack_icmp.icmp_data[PHDR_LEN+i])
883 break;
884 }
885 PR_PACK_SUB();
886 (void)printf("\nwrong data byte #%d should have been"
887 " %#x but was %#x",
888 i, (u_char)opack_icmp.icmp_data[i],
889 (u_char)icp->icmp_data[i]);
890 for (i=PHDR_LEN; i<datalen; i++) {
891 if ((i%16) == PHDR_LEN)
892 (void)printf("\n\t");
893 (void)printf("%2x ",(u_char)icp->icmp_data[i]);
894 }
895 }
896
897 } else {
898 if (!pr_icmph(icp, from, net_len))
899 return;
900 dumped = 2;
901 }
902
903 /* Display any IP options */
904 cp = buf + sizeof(struct ip);
905 while (hlen > (int)sizeof(struct ip)) {
906 switch (*cp) {
907 case IPOPT_EOL:
908 hlen = 0;
909 break;
910 case IPOPT_LSRR:
911 hlen -= 2;
912 j = *++cp;
913 ++cp;
914 j -= IPOPT_MINOFF;
915 if (j <= 0)
916 continue;
917 if (dumped <= 1) {
918 j = ((j+3)/4)*4;
919 hlen -= j;
920 cp += j;
921 break;
922 }
923 PR_PACK_SUB();
924 (void)printf("\nLSRR: ");
925 for (;;) {
926 pr_saddr("\t%s", cp);
927 cp += 4;
928 hlen -= 4;
929 j -= 4;
930 if (j <= 0)
931 break;
932 (void)putchar('\n');
933 }
934 break;
935 case IPOPT_RR:
936 j = *++cp; /* get length */
937 i = *++cp; /* and pointer */
938 hlen -= 2;
939 if (i > j)
940 i = j;
941 i -= IPOPT_MINOFF;
942 if (i <= 0)
943 continue;
944 if (dumped <= 1) {
945 if (i == old_rrlen
946 && !memcmp(cp, old_rr, i)) {
947 if (dumped)
948 (void)printf("\t(same route)");
949 j = ((i+3)/4)*4;
950 hlen -= j;
951 cp += j;
952 break;
953 }
954 old_rrlen = i;
955 (void) memcpy(old_rr, cp, i);
956 }
957 if (!dumped) {
958 jiggle_flush(1);
959 (void)printf("RR: ");
960 dumped = 1;
961 } else {
962 (void)printf("\nRR: ");
963 }
964 for (;;) {
965 pr_saddr("\t%s", cp);
966 cp += 4;
967 hlen -= 4;
968 i -= 4;
969 if (i <= 0)
970 break;
971 (void)putchar('\n');
972 }
973 break;
974 case IPOPT_NOP:
975 if (dumped <= 1)
976 break;
977 PR_PACK_SUB();
978 (void)printf("\nNOP");
979 break;
980 #ifdef sgi
981 case IPOPT_SECURITY: /* RFC 1108 RIPSO BSO */
982 case IPOPT_ESO: /* RFC 1108 RIPSO ESO */
983 case IPOPT_CIPSO: /* Commercial IPSO */
984 if ((sysconf(_SC_IP_SECOPTS)) > 0) {
985 i = (unsigned)cp[1];
986 hlen -= i - 1;
987 PR_PACK_SUB();
988 (void)printf("\nSEC:");
989 while (i--) {
990 (void)printf(" %02x", *cp++);
991 }
992 cp--;
993 break;
994 }
995 #endif
996 default:
997 PR_PACK_SUB();
998 (void)printf("\nunknown option 0x%x", *cp);
999 break;
1000 }
1001 hlen--;
1002 cp++;
1003 }
1004
1005 if (dumped) {
1006 (void)putchar('\n');
1007 (void)fflush(stdout);
1008 } else {
1009 jiggle(-1);
1010 }
1011 }
1012
1013
1014 /* Compute the IP checksum
1015 * This assumes the packet is less than 32K long.
1016 */
1017 static u_short
1018 in_cksum(u_short *p,
1019 u_int len)
1020 {
1021 u_int sum = 0;
1022 int nwords = len >> 1;
1023
1024 while (nwords-- != 0)
1025 sum += *p++;
1026
1027 if (len & 1) {
1028 union {
1029 u_short w;
1030 u_char c[2];
1031 } u;
1032 u.c[0] = *(u_char *)p;
1033 u.c[1] = 0;
1034 sum += u.w;
1035 }
1036
1037 /* end-around-carry */
1038 sum = (sum >> 16) + (sum & 0xffff);
1039 sum += (sum >> 16);
1040 return (~sum);
1041 }
1042
1043
1044 /*
1045 * compute the difference of two timevals in seconds
1046 */
1047 static double
1048 diffsec(struct timeval *now,
1049 struct timeval *then)
1050 {
1051 return ((now->tv_sec - then->tv_sec)*1.0
1052 + (now->tv_usec - then->tv_usec)/1000000.0);
1053 }
1054
1055
1056 static void
1057 timevaladd(struct timeval *t1,
1058 struct timeval *t2)
1059 {
1060
1061 t1->tv_sec += t2->tv_sec;
1062 if ((t1->tv_usec += t2->tv_usec) >= 1000000) {
1063 t1->tv_sec++;
1064 t1->tv_usec -= 1000000;
1065 }
1066 }
1067
1068
1069 static void
1070 sec_to_timeval(const double sec, struct timeval *tp)
1071 {
1072 tp->tv_sec = sec;
1073 tp->tv_usec = (sec - tp->tv_sec) * 1000000.0;
1074 }
1075
1076
1077 static double
1078 timeval_to_sec(const struct timeval *tp)
1079 {
1080 return tp->tv_sec + tp->tv_usec / 1000000.0;
1081 }
1082
1083
1084 /*
1085 * Print statistics.
1086 * Heavily buffered STDIO is used here, so that all the statistics
1087 * will be written with 1 sys-write call. This is nice when more
1088 * than one copy of the program is running on a terminal; it prevents
1089 * the statistics output from becomming intermingled.
1090 */
1091 static void
1092 summary(int header)
1093 {
1094 jiggle_flush(1);
1095
1096 if (header)
1097 (void)printf("\n----%s PING Statistics----\n", hostname);
1098 (void)printf("%d packets transmitted, ", ntransmitted);
1099 (void)printf("%d packets received, ", nreceived);
1100 if (nrepeats)
1101 (void)printf("+%d duplicates, ", nrepeats);
1102 if (ntransmitted) {
1103 if (nreceived > ntransmitted)
1104 (void)printf("-- somebody's printing up packets!");
1105 else
1106 (void)printf("%.1f%% packet loss",
1107 (((ntransmitted-nreceived)*100.0) /
1108 ntransmitted));
1109 }
1110 (void)printf("\n");
1111 if (nreceived && (pingflags & F_TIMING)) {
1112 double n = nreceived + nrepeats;
1113 double avg = (tsum / n);
1114 double variance = 0.0;
1115 if (n>1)
1116 variance = (tsumsq - n*avg*avg) /(n-1);
1117
1118 printf("round-trip min/avg/max/stddev = "
1119 "%.3f/%.3f/%.3f/%.3f ms\n",
1120 tmin * 1000.0, avg * 1000.0,
1121 tmax * 1000.0, sqrt(variance) * 1000.0);
1122 if (pingflags & F_FLOOD) {
1123 double r = diffsec(&last_rx, &first_rx);
1124 double t = diffsec(&last_tx, &first_tx);
1125 if (r == 0)
1126 r = 0.0001;
1127 if (t == 0)
1128 t = 0.0001;
1129 (void)printf(" %.1f packets/sec sent, "
1130 " %.1f packets/sec received\n",
1131 ntransmitted/t, nreceived/r);
1132 }
1133 }
1134 }
1135
1136
1137 /*
1138 * Print statistics when SIGINFO is received.
1139 */
1140 /* ARGSUSED */
1141 static void
1142 prtsig(int s)
1143 {
1144 summary(0);
1145 #ifdef SIGINFO
1146 (void)signal(SIGINFO, prtsig);
1147 #else
1148 (void)signal(SIGQUIT, prtsig);
1149 #endif
1150 }
1151
1152
1153 /*
1154 * On the first SIGINT, allow any outstanding packets to dribble in
1155 */
1156 static void
1157 prefinish(int s)
1158 {
1159 if (lastrcvd /* quit now if caught up */
1160 || nreceived == 0) /* or if remote is dead */
1161 finish(0);
1162
1163 (void)signal(s, finish); /* do this only the 1st time */
1164
1165 if (npackets > ntransmitted) /* let the normal limit work */
1166 npackets = ntransmitted;
1167 }
1168
1169
1170 /*
1171 * Print statistics and give up.
1172 */
1173 /* ARGSUSED */
1174 static void
1175 finish(int s)
1176 {
1177 #if defined(SIGINFO) && defined(NOKERNINFO)
1178 struct termios ts;
1179
1180 if (reset_kerninfo && tcgetattr (0, &ts) != -1) {
1181 ts.c_lflag &= ~NOKERNINFO;
1182 tcsetattr (0, TCSANOW, &ts);
1183 }
1184 (void)signal(SIGINFO, SIG_IGN);
1185 #else
1186 (void)signal(SIGQUIT, SIG_DFL);
1187 #endif
1188
1189 summary(1);
1190 exit(nreceived > 0 ? 0 : 2);
1191 }
1192
1193
1194 static int /* 0=do not print it */
1195 ck_pr_icmph(struct icmp *icp,
1196 struct sockaddr_in *from,
1197 int cc,
1198 int override) /* 1=override VERBOSE if interesting */
1199 {
1200 int hlen;
1201 struct ip ipb, *ip = &ipb;
1202 struct icmp icp2b, *icp2 = &icp2b;
1203 int res;
1204
1205 if (pingflags & F_VERBOSE) {
1206 res = 1;
1207 jiggle_flush(1);
1208 } else {
1209 res = 0;
1210 }
1211
1212 (void) memcpy(ip, icp->icmp_data, sizeof(*ip));
1213 hlen = ip->ip_hl << 2;
1214 if (ip->ip_p == IPPROTO_ICMP
1215 && hlen + 6 <= cc) {
1216 (void) memcpy(icp2, &icp->icmp_data[hlen], sizeof(*icp2));
1217 if (icp2->icmp_id == ident) {
1218 /* remember to clear route cached in kernel
1219 * if this non-Echo-Reply ICMP message was for one
1220 * of our packets.
1221 */
1222 clear_cache.tv_sec = 0;
1223
1224 if (!res && override
1225 && (pingflags & (F_QUIET|F_SEMI_QUIET)) == 0) {
1226 jiggle_flush(1);
1227 (void)printf("%d bytes from %s: ",
1228 cc, pr_addr(&from->sin_addr));
1229 res = 1;
1230 }
1231 }
1232 }
1233
1234 return res;
1235 }
1236
1237
1238 /*
1239 * Print a descriptive string about an ICMP header other than an echo reply.
1240 */
1241 static int /* 0=printed nothing */
1242 pr_icmph(struct icmp *icp,
1243 struct sockaddr_in *from,
1244 int cc)
1245 {
1246 switch (icp->icmp_type ) {
1247 case ICMP_UNREACH:
1248 if (!ck_pr_icmph(icp, from, cc, 1))
1249 return 0;
1250 switch (icp->icmp_code) {
1251 case ICMP_UNREACH_NET:
1252 (void)printf("Destination Net Unreachable");
1253 break;
1254 case ICMP_UNREACH_HOST:
1255 (void)printf("Destination Host Unreachable");
1256 break;
1257 case ICMP_UNREACH_PROTOCOL:
1258 (void)printf("Destination Protocol Unreachable");
1259 break;
1260 case ICMP_UNREACH_PORT:
1261 (void)printf("Destination Port Unreachable");
1262 break;
1263 case ICMP_UNREACH_NEEDFRAG:
1264 (void)printf("frag needed and DF set. Next MTU=%d",
1265 ntohs(icp->icmp_nextmtu));
1266 break;
1267 case ICMP_UNREACH_SRCFAIL:
1268 (void)printf("Source Route Failed");
1269 break;
1270 case ICMP_UNREACH_NET_UNKNOWN:
1271 (void)printf("Unreachable unknown net");
1272 break;
1273 case ICMP_UNREACH_HOST_UNKNOWN:
1274 (void)printf("Unreachable unknown host");
1275 break;
1276 case ICMP_UNREACH_ISOLATED:
1277 (void)printf("Unreachable host isolated");
1278 break;
1279 case ICMP_UNREACH_NET_PROHIB:
1280 (void)printf("Net prohibited access");
1281 break;
1282 case ICMP_UNREACH_HOST_PROHIB:
1283 (void)printf("Host prohibited access");
1284 break;
1285 case ICMP_UNREACH_TOSNET:
1286 (void)printf("Bad TOS for net");
1287 break;
1288 case ICMP_UNREACH_TOSHOST:
1289 (void)printf("Bad TOS for host");
1290 break;
1291 case 13:
1292 (void)printf("Communication prohibited");
1293 break;
1294 case 14:
1295 (void)printf("Host precedence violation");
1296 break;
1297 case 15:
1298 (void)printf("Precedence cutoff");
1299 break;
1300 default:
1301 (void)printf("Bad Destination Unreachable Code: %d",
1302 icp->icmp_code);
1303 break;
1304 }
1305 /* Print returned IP header information */
1306 pr_retip(icp, cc);
1307 break;
1308
1309 case ICMP_SOURCEQUENCH:
1310 if (!ck_pr_icmph(icp, from, cc, 1))
1311 return 0;
1312 (void)printf("Source Quench");
1313 pr_retip(icp, cc);
1314 break;
1315
1316 case ICMP_REDIRECT:
1317 if (!ck_pr_icmph(icp, from, cc, 1))
1318 return 0;
1319 switch (icp->icmp_code) {
1320 case ICMP_REDIRECT_NET:
1321 (void)printf("Redirect Network");
1322 break;
1323 case ICMP_REDIRECT_HOST:
1324 (void)printf("Redirect Host");
1325 break;
1326 case ICMP_REDIRECT_TOSNET:
1327 (void)printf("Redirect Type of Service and Network");
1328 break;
1329 case ICMP_REDIRECT_TOSHOST:
1330 (void)printf("Redirect Type of Service and Host");
1331 break;
1332 default:
1333 (void)printf("Redirect--Bad Code: %d", icp->icmp_code);
1334 break;
1335 }
1336 (void)printf(" New router addr: %s",
1337 pr_addr(&icp->icmp_hun.ih_gwaddr));
1338 pr_retip(icp, cc);
1339 break;
1340
1341 case ICMP_ECHO:
1342 if (!ck_pr_icmph(icp, from, cc, 0))
1343 return 0;
1344 (void)printf("Echo Request: ID=%d seq=%d",
1345 ntohs(icp->icmp_id), ntohs(icp->icmp_seq));
1346 break;
1347
1348 case ICMP_ECHOREPLY:
1349 /* displaying other's pings is too noisey */
1350 #if 0
1351 if (!ck_pr_icmph(icp, from, cc, 0))
1352 return 0;
1353 (void)printf("Echo Reply: ID=%d seq=%d",
1354 ntohs(icp->icmp_id), ntohs(icp->icmp_seq));
1355 break;
1356 #else
1357 return 0;
1358 #endif
1359
1360 case ICMP_ROUTERADVERT:
1361 if (!ck_pr_icmph(icp, from, cc, 0))
1362 return 0;
1363 (void)printf("Router Discovery Advert");
1364 break;
1365
1366 case ICMP_ROUTERSOLICIT:
1367 if (!ck_pr_icmph(icp, from, cc, 0))
1368 return 0;
1369 (void)printf("Router Discovery Solicit");
1370 break;
1371
1372 case ICMP_TIMXCEED:
1373 if (!ck_pr_icmph(icp, from, cc, 1))
1374 return 0;
1375 switch (icp->icmp_code ) {
1376 case ICMP_TIMXCEED_INTRANS:
1377 (void)printf("Time To Live exceeded");
1378 break;
1379 case ICMP_TIMXCEED_REASS:
1380 (void)printf("Frag reassembly time exceeded");
1381 break;
1382 default:
1383 (void)printf("Time exceeded, Bad Code: %d",
1384 icp->icmp_code);
1385 break;
1386 }
1387 pr_retip(icp, cc);
1388 break;
1389
1390 case ICMP_PARAMPROB:
1391 if (!ck_pr_icmph(icp, from, cc, 1))
1392 return 0;
1393 (void)printf("Parameter problem: pointer = 0x%02x",
1394 icp->icmp_hun.ih_pptr);
1395 pr_retip(icp, cc);
1396 break;
1397
1398 case ICMP_TSTAMP:
1399 if (!ck_pr_icmph(icp, from, cc, 0))
1400 return 0;
1401 (void)printf("Timestamp");
1402 break;
1403
1404 case ICMP_TSTAMPREPLY:
1405 if (!ck_pr_icmph(icp, from, cc, 0))
1406 return 0;
1407 (void)printf("Timestamp Reply");
1408 break;
1409
1410 case ICMP_IREQ:
1411 if (!ck_pr_icmph(icp, from, cc, 0))
1412 return 0;
1413 (void)printf("Information Request");
1414 break;
1415
1416 case ICMP_IREQREPLY:
1417 if (!ck_pr_icmph(icp, from, cc, 0))
1418 return 0;
1419 (void)printf("Information Reply");
1420 break;
1421
1422 case ICMP_MASKREQ:
1423 if (!ck_pr_icmph(icp, from, cc, 0))
1424 return 0;
1425 (void)printf("Address Mask Request");
1426 break;
1427
1428 case ICMP_MASKREPLY:
1429 if (!ck_pr_icmph(icp, from, cc, 0))
1430 return 0;
1431 (void)printf("Address Mask Reply");
1432 break;
1433
1434 default:
1435 if (!ck_pr_icmph(icp, from, cc, 0))
1436 return 0;
1437 (void)printf("Bad ICMP type: %d", icp->icmp_type);
1438 if (pingflags & F_VERBOSE)
1439 pr_iph(icp, cc);
1440 }
1441
1442 return 1;
1443 }
1444
1445
1446 /*
1447 * Print an IP header with options.
1448 */
1449 static void
1450 pr_iph(struct icmp *icp,
1451 int cc)
1452 {
1453 int hlen;
1454 u_char *cp;
1455 struct ip ipb, *ip = &ipb;
1456
1457 (void) memcpy(ip, icp->icmp_data, sizeof(*ip));
1458
1459 hlen = ip->ip_hl << 2;
1460 cp = (u_char *) &icp->icmp_data[20]; /* point to options */
1461
1462 (void)printf("\n Vr HL TOS Len ID Flg off TTL Pro cks Src Dst\n");
1463 (void)printf(" %1x %1x %02x %04x %04x",
1464 ip->ip_v, ip->ip_hl, ip->ip_tos, ip->ip_len, ip->ip_id);
1465 (void)printf(" %1x %04x",
1466 ((ip->ip_off)&0xe000)>>13, (ip->ip_off)&0x1fff);
1467 (void)printf(" %02x %02x %04x",
1468 ip->ip_ttl, ip->ip_p, ip->ip_sum);
1469 (void)printf(" %15s ",
1470 inet_ntoa(*(struct in_addr *)&ip->ip_src.s_addr));
1471 (void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_dst.s_addr));
1472 /* dump any option bytes */
1473 while (hlen-- > 20 && cp < (u_char*)icp+cc) {
1474 (void)printf("%02x", *cp++);
1475 }
1476 }
1477
1478 /*
1479 * Print an ASCII host address starting from a string of bytes.
1480 */
1481 static void
1482 pr_saddr(char *pat,
1483 u_char *cp)
1484 {
1485 n_long l;
1486 struct in_addr addr;
1487
1488 l = (u_char)*++cp;
1489 l = (l<<8) + (u_char)*++cp;
1490 l = (l<<8) + (u_char)*++cp;
1491 l = (l<<8) + (u_char)*++cp;
1492 addr.s_addr = htonl(l);
1493 (void)printf(pat, (l == 0) ? "0.0.0.0" : pr_addr(&addr));
1494 }
1495
1496
1497 /*
1498 * Return an ASCII host address
1499 * as a dotted quad and optionally with a hostname
1500 */
1501 static char *
1502 pr_addr(struct in_addr *addr) /* in network order */
1503 {
1504 struct hostent *hp;
1505 static char buf[MAXHOSTNAMELEN+4+16+1];
1506
1507 if ((pingflags & F_NUMERIC)
1508 || !(hp = gethostbyaddr((char *)addr, sizeof(*addr), AF_INET))) {
1509 (void)snprintf(buf, sizeof(buf), "%s", inet_ntoa(*addr));
1510 } else {
1511 (void)snprintf(buf, sizeof(buf), "%s (%s)", hp->h_name,
1512 inet_ntoa(*addr));
1513 }
1514
1515 return buf;
1516 }
1517
1518 /*
1519 * Dump some info on a returned (via ICMP) IP packet.
1520 */
1521 static void
1522 pr_retip(struct icmp *icp,
1523 int cc)
1524 {
1525 int hlen;
1526 u_char *cp;
1527 struct ip ipb, *ip = &ipb;
1528
1529 (void) memcpy(ip, icp->icmp_data, sizeof(*ip));
1530
1531 if (pingflags & F_VERBOSE)
1532 pr_iph(icp, cc);
1533
1534 hlen = ip->ip_hl << 2;
1535 cp = (u_char *) &icp->icmp_data[hlen];
1536
1537 if (ip->ip_p == IPPROTO_TCP) {
1538 if (pingflags & F_VERBOSE)
1539 (void)printf("\n TCP: from port %u, to port %u",
1540 (*cp*256+*(cp+1)), (*(cp+2)*256+*(cp+3)));
1541 } else if (ip->ip_p == IPPROTO_UDP) {
1542 if (pingflags & F_VERBOSE)
1543 (void)printf("\n UDP: from port %u, to port %u",
1544 (*cp*256+*(cp+1)), (*(cp+2)*256+*(cp+3)));
1545 } else if (ip->ip_p == IPPROTO_ICMP) {
1546 struct icmp icp2;
1547 (void) memcpy(&icp2, cp, sizeof(icp2));
1548 if (icp2.icmp_type == ICMP_ECHO) {
1549 if (pingflags & F_VERBOSE)
1550 (void)printf("\n ID=%u icmp_seq=%u",
1551 ntohs((u_short)icp2.icmp_id),
1552 ntohs((u_short)icp2.icmp_seq));
1553 else
1554 (void)printf(" for icmp_seq=%u",
1555 ntohs((u_short)icp2.icmp_seq));
1556 }
1557 }
1558 }
1559
1560 static void
1561 fill(void)
1562 {
1563 int i, j, k;
1564 char *cp;
1565 int pat[16];
1566
1567 for (cp = fill_pat; *cp != '\0'; cp++) {
1568 if (!isxdigit((unsigned char)*cp))
1569 break;
1570 }
1571 if (cp == fill_pat || *cp != '\0' || (cp-fill_pat) > 16*2) {
1572 (void)fflush(stdout);
1573 errx(1, "\"-p %s\": patterns must be specified with"
1574 " 1-32 hex digits\n",
1575 fill_pat);
1576 }
1577
1578 i = sscanf(fill_pat,
1579 "%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x",
1580 &pat[0], &pat[1], &pat[2], &pat[3],
1581 &pat[4], &pat[5], &pat[6], &pat[7],
1582 &pat[8], &pat[9], &pat[10], &pat[11],
1583 &pat[12], &pat[13], &pat[14], &pat[15]);
1584
1585 for (k=PHDR_LEN, j = 0; k <= datalen; k++) {
1586 opack_icmp.icmp_data[k] = pat[j];
1587 if (++j >= i)
1588 j = 0;
1589 }
1590
1591 if (!(pingflags & F_QUIET)) {
1592 (void)printf("PATTERN: 0x");
1593 for (j=0; j<i; j++)
1594 (void)printf("%02x",
1595 (u_char)opack_icmp.icmp_data[PHDR_LEN+j]);
1596 (void)printf("\n");
1597 }
1598
1599 }
1600
1601
1602 static void
1603 rnd_fill(void)
1604 {
1605 static u_int32_t rnd;
1606 int i;
1607
1608 for (i = PHDR_LEN; i < datalen; i++) {
1609 rnd = (3141592621U * rnd + 663896637U);
1610 opack_icmp.icmp_data[i] = rnd>>24;
1611 }
1612 }
1613
1614
1615 static void
1616 gethost(const char *arg,
1617 const char *name,
1618 struct sockaddr_in *sa,
1619 char *realname,
1620 int realname_len)
1621 {
1622 struct hostent *hp;
1623
1624 (void)memset(sa, 0, sizeof(*sa));
1625 sa->sin_family = AF_INET;
1626
1627 /* If it is an IP address, try to convert it to a name to
1628 * have something nice to display.
1629 */
1630 if (inet_aton(name, &sa->sin_addr) != 0) {
1631 if (realname) {
1632 if (pingflags & F_NUMERIC)
1633 hp = 0;
1634 else
1635 hp = gethostbyaddr((char *)&sa->sin_addr,
1636 sizeof(sa->sin_addr),
1637 AF_INET);
1638 (void)strncpy(realname, hp ? hp->h_name : name,
1639 realname_len);
1640 realname[realname_len-1] = '\0';
1641 }
1642 return;
1643 }
1644
1645 hp = gethostbyname(name);
1646 if (!hp)
1647 errx(1, "Cannot resolve \"%s\" (%s)",name,hstrerror(h_errno));
1648
1649 if (hp->h_addrtype != AF_INET)
1650 errx(1, "%s only supported with IP", arg);
1651
1652 (void)memcpy(&sa->sin_addr, hp->h_addr, sizeof(sa->sin_addr));
1653
1654 if (realname) {
1655 (void)strncpy(realname, hp->h_name, realname_len);
1656 realname[realname_len-1] = '\0';
1657 }
1658 }
1659
1660
1661 static void
1662 usage(void)
1663 {
1664
1665 (void)fprintf(stderr, "Usage: \n"
1666 "%s [-dDfLnoPqQrRv] [-c count] [-g gateway] [-h host]"
1667 " [-i interval] [-I addr]\n"
1668 " [-l preload] [-p pattern] [-s size] [-t tos] [-T ttl]"
1669 " [-w maxwait] host\n",
1670 __progname);
1671 exit(1);
1672 }
1673