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