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