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