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