ping.c revision 1.21 1 /* $NetBSD: ping.c,v 1.21 1996/11/06 20:42:17 cgd 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 #ifndef lint
40 static char copyright[] =
41 "@(#) Copyright (c) 1989, 1993\n\
42 The Regents of the University of California. All rights reserved.\n";
43 #endif /* not lint */
44
45 #ifndef lint
46 #if 0
47 static char sccsid[] = "@(#)ping.c 8.1 (Berkeley) 6/5/93";
48 #else
49 static char rcsid[] = "$NetBSD: ping.c,v 1.21 1996/11/06 20:42:17 cgd Exp $";
50 #endif
51 #endif /* not lint */
52
53 /*
54 * P I N G . C
55 *
56 * Using the InterNet Control Message Protocol (ICMP) "ECHO" facility,
57 * measure round-trip-delays and packet loss across network paths.
58 *
59 * Author -
60 * Mike Muuss
61 * U. S. Army Ballistic Research Laboratory
62 * December, 1983
63 *
64 * Status -
65 * Public Domain. Distribution Unlimited.
66 * Bugs -
67 * More statistics could always be gathered.
68 * This program has to run SUID to ROOT to access the ICMP socket.
69 */
70
71 #include <sys/param.h>
72 #include <sys/queue.h>
73 #include <sys/socket.h>
74 #include <sys/file.h>
75 #include <sys/time.h>
76
77 #include <netinet/in_systm.h>
78 #include <netinet/in.h>
79 #include <netinet/ip.h>
80 #include <netinet/ip_icmp.h>
81 #include <netinet/ip_var.h>
82 #include <arpa/inet.h>
83 #include <netdb.h>
84 #include <signal.h>
85 #include <unistd.h>
86 #include <stdio.h>
87 #include <ctype.h>
88 #include <err.h>
89 #include <errno.h>
90 #include <string.h>
91 #include <stdlib.h>
92
93 #define DEFDATALEN (64 - 8) /* default data length */
94 #define MAXIPLEN 60
95 #define MAXICMPLEN 76
96 #define MAXPACKET (65536 - 60 - 8)/* max packet size */
97 #define MAXWAIT_DEFAULT 10 /* max seconds to wait for response */
98 #define NROUTES 9 /* number of record route slots */
99
100 #define A(bit) rcvd_tbl[(bit)>>3] /* identify byte in array */
101 #define B(bit) (1 << ((bit) & 0x07)) /* identify bit in byte */
102 #define SET(bit) (A(bit) |= B(bit))
103 #define CLR(bit) (A(bit) &= (~B(bit)))
104 #define TST(bit) (A(bit) & B(bit))
105
106 /* various options */
107 int options;
108 #define F_FLOOD 0x001
109 #define F_INTERVAL 0x002
110 #define F_NUMERIC 0x004
111 #define F_PINGFILLED 0x008
112 #define F_QUIET 0x010
113 #define F_RROUTE 0x020
114 #define F_SO_DEBUG 0x040
115 #define F_SO_DONTROUTE 0x080
116 #define F_VERBOSE 0x100
117 #define F_SADDR 0x200
118
119 /* multicast options */
120 int moptions;
121 #define MULTICAST_NOLOOP 0x001
122 #define MULTICAST_TTL 0x002
123 #define MULTICAST_IF 0x004
124
125 /*
126 * MAX_DUP_CHK is the number of bits in received table, i.e. the maximum
127 * number of received sequence numbers we can keep track of. Change 128
128 * to 8192 for complete accuracy...
129 */
130 #define MAX_DUP_CHK (8 * 128)
131 int mx_dup_ck = MAX_DUP_CHK;
132 char rcvd_tbl[MAX_DUP_CHK / 8];
133
134 struct sockaddr whereto; /* who to ping */
135 struct sockaddr_in whence; /* Which interface we come from */
136 int datalen = DEFDATALEN;
137 int s; /* socket file descriptor */
138 u_char outpack[MAXPACKET];
139 char BSPACE = '\b'; /* characters written for flood */
140 char DOT = '.';
141 char *hostname;
142 int ident; /* process id to identify our packets */
143
144 /* counters */
145 long npackets; /* max packets to transmit */
146 long nreceived; /* # of packets we got back */
147 long nrepeats; /* number of duplicates */
148 long ntransmitted; /* sequence # for outbound packets = #sent */
149 int interval = 1; /* interval between packets */
150
151 /* timing */
152 int timing; /* flag to do timing */
153 int maxwait = MAXWAIT_DEFAULT; /* max seconds to wait for response */
154 double tmin = 999999999.0; /* minimum round trip time */
155 double tmax = 0.0; /* maximum round trip time */
156 double tsum = 0.0; /* sum of all times, for doing average */
157
158 void fill __P((char *, char *));
159 void catcher(), finish(), statistics();
160 int in_cksum __P((u_short *, int));
161 void pinger();
162 char *pr_addr __P((u_long));
163 void pr_icmph __P((struct icmp *));
164 void pr_pack __P((char *, int, struct sockaddr_in *));
165 void pr_retip __P((struct ip *));
166 void pr_stats __P((void));
167 void usage();
168
169 int
170 main(argc, argv)
171 int argc;
172 char **argv;
173 {
174 extern int errno, optind;
175 extern char *optarg;
176 struct timeval timeout;
177 struct hostent *hp;
178 struct sockaddr_in *to;
179 struct protoent *proto;
180 struct in_addr ifaddr, saddr;
181 register int i;
182 int ch, fdmask, hold, packlen, preload;
183 u_char *datap, *packet;
184 char *target, hnamebuf[MAXHOSTNAMELEN];
185 u_char ttl, loop = 1;
186 #ifdef IP_OPTIONS
187 char rspace[3 + 4 * NROUTES + 1]; /* record route space */
188 #endif
189
190 preload = 0;
191 datap = &outpack[8 + sizeof(struct timeval)];
192 while ((ch = getopt(argc, argv, "I:LRS:c:dfh:i:l:np:qrs:t:vw:")) != EOF)
193 switch(ch) {
194 case 'c':
195 npackets = atoi(optarg);
196 if (npackets <= 0)
197 errx(1, "bad number of packets to transmit: %s",
198 optarg);
199 break;
200 case 'd':
201 options |= F_SO_DEBUG;
202 break;
203 case 'f':
204 if (getuid())
205 errx(1, "%s", strerror(EPERM));
206 options |= F_FLOOD;
207 setbuf(stdout, (char *)NULL);
208 break;
209 case 'I':
210 if (inet_aton(optarg, &ifaddr) == 0)
211 errx(1, "bad interface address: %s", optarg);
212 moptions |= MULTICAST_IF;
213 break;
214 case 'i': /* wait between sending packets */
215 interval = atoi(optarg);
216 if (interval <= 0)
217 errx(1, "bad timing interval: %s", optarg);
218 options |= F_INTERVAL;
219 break;
220 case 'L':
221 moptions |= MULTICAST_NOLOOP;
222 loop = 0;
223 break;
224 case 'l':
225 preload = atoi(optarg);
226 if (preload < 0)
227 errx(1, "bad preload value: %s", optarg);
228 break;
229 case 'n':
230 options |= F_NUMERIC;
231 break;
232 case 'p': /* fill buffer with user pattern */
233 options |= F_PINGFILLED;
234 fill((char *)datap, optarg);
235 break;
236 case 'q':
237 options |= F_QUIET;
238 break;
239 case 'R':
240 options |= F_RROUTE;
241 break;
242 case 'r':
243 options |= F_SO_DONTROUTE;
244 break;
245 case 'S':
246 if (inet_aton(optarg, &saddr) == 0) {
247 if ((hp = gethostbyname(optarg)) == NULL)
248 errx(1, "bad interface address: %s",
249 optarg);
250 memcpy(&saddr, hp->h_addr, sizeof(saddr));
251 }
252 options |= F_SADDR;
253 break;
254 case 's': /* size of packet to send */
255 datalen = atoi(optarg);
256 if (datalen <= 0)
257 errx(1, "bad packet size: %s", optarg);
258 if (datalen > MAXPACKET)
259 errx(1, "packet size too large: %s", optarg);
260 break;
261 case 't':
262 ttl = atoi(optarg);
263 if (ttl <= 0)
264 errx(1, "bad ttl value: %s", optarg);
265 if (ttl > 255)
266 errx(1, "ttl value too large: %s", optarg);
267 moptions |= MULTICAST_TTL;
268 break;
269 case 'v':
270 options |= F_VERBOSE;
271 break;
272 case 'w':
273 maxwait = atoi(optarg);
274 if (maxwait <= 0)
275 errx(1, "bad maxwait value: %s", optarg);
276 break;
277 default:
278 usage();
279 }
280 argc -= optind;
281 argv += optind;
282
283 if (argc != 1)
284 usage();
285 target = *argv;
286
287 memset(&whereto, 0, sizeof(struct sockaddr));
288 to = (struct sockaddr_in *)&whereto;
289 to->sin_len = sizeof(struct sockaddr_in);
290 to->sin_family = AF_INET;
291 if (inet_aton(target, &to->sin_addr) != 0)
292 hostname = target;
293 else {
294 hp = gethostbyname(target);
295 if (!hp)
296 errx(1, "unknown host: %s", target);
297 to->sin_family = hp->h_addrtype;
298 memcpy(&to->sin_addr, hp->h_addr, hp->h_length);
299 (void)strncpy(hnamebuf, hp->h_name, sizeof(hnamebuf) - 1);
300 hostname = hnamebuf;
301 }
302
303 if (options & F_FLOOD && options & F_INTERVAL)
304 errx(1, "-f and -i options are incompatible");
305
306 if (datalen >= sizeof(struct timeval)) /* can we time transfer */
307 timing = 1;
308 packlen = datalen + MAXIPLEN + MAXICMPLEN;
309 if (!(packet = (u_char *)malloc((u_int)packlen)))
310 err(1, "malloc");
311 if (!(options & F_PINGFILLED))
312 for (i = 8; i < datalen; ++i)
313 *datap++ = i;
314
315 ident = getpid() & 0xFFFF;
316
317 if (!(proto = getprotobyname("icmp")))
318 errx(1, "unknown protocol icmp");
319 if ((s = socket(AF_INET, SOCK_RAW, proto->p_proto)) < 0)
320 err(1, "socket");
321 hold = 1;
322
323 if (options & F_SADDR) {
324 memset(&whence, 0, sizeof(whence));
325 whence.sin_len = sizeof(whence);
326 whence.sin_family = AF_INET;
327 memcpy(&whence.sin_addr.s_addr, &saddr, sizeof(saddr));
328 if (bind(s, (struct sockaddr*)&whence, sizeof(whence)) < 0)
329 err(1, "bind");
330 }
331
332 if (options & F_SO_DEBUG)
333 (void)setsockopt(s, SOL_SOCKET, SO_DEBUG, (char *)&hold,
334 sizeof(hold));
335 if (options & F_SO_DONTROUTE)
336 (void)setsockopt(s, SOL_SOCKET, SO_DONTROUTE, (char *)&hold,
337 sizeof(hold));
338
339 /* record route option */
340 if (options & F_RROUTE) {
341 #ifdef IP_OPTIONS
342 rspace[IPOPT_OPTVAL] = IPOPT_RR;
343 rspace[IPOPT_OLEN] = sizeof(rspace)-1;
344 rspace[IPOPT_OFFSET] = IPOPT_MINOFF;
345 if (setsockopt(s, IPPROTO_IP, IP_OPTIONS, rspace,
346 sizeof(rspace)) < 0) {
347 perror("ping: record route");
348 exit(1);
349 }
350 #else
351 errx(1, "record route not available in this implementation");
352 #endif /* IP_OPTIONS */
353 }
354
355 if ((moptions & MULTICAST_NOLOOP) &&
356 setsockopt(s, IPPROTO_IP, IP_MULTICAST_LOOP, &loop,
357 sizeof(loop)) < 0)
358 err(1, "setsockopt IP_MULTICAST_LOOP");
359 if ((moptions & MULTICAST_TTL) &&
360 setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL, &ttl,
361 sizeof(ttl)) < 0)
362 err(1, "setsockopt IP_MULTICAST_TTL");
363 if ((moptions & MULTICAST_IF) &&
364 setsockopt(s, IPPROTO_IP, IP_MULTICAST_IF, &ifaddr,
365 sizeof(ifaddr)) < 0)
366 err(1, "setsockopt IP_MULTICAST_IF");
367
368 /*
369 * When pinging the broadcast address, you can get a lot of answers.
370 * Doing something so evil is useful if you are trying to stress the
371 * ethernet, or just want to fill the arp cache to get some stuff for
372 * /etc/ethers.
373 */
374 hold = 48 * 1024;
375 (void)setsockopt(s, SOL_SOCKET, SO_RCVBUF, (char *)&hold,
376 sizeof(hold));
377
378 if (to->sin_family == AF_INET)
379 (void)printf("PING %s (%s): %d data bytes\n", hostname,
380 inet_ntoa(*(struct in_addr *)&to->sin_addr.s_addr),
381 datalen);
382 else
383 (void)printf("PING %s: %d data bytes\n", hostname, datalen);
384
385 (void)signal(SIGINFO, statistics);
386 (void)signal(SIGINT, finish);
387 (void)signal(SIGALRM, catcher);
388
389 while (preload--) /* fire off them quickies */
390 pinger();
391
392 if ((options & F_FLOOD) == 0)
393 catcher(); /* start things going */
394
395 for (;;) {
396 struct sockaddr_in from;
397 register int cc;
398 int fromlen;
399
400 if (options & F_FLOOD) {
401 pinger();
402 timeout.tv_sec = 0;
403 timeout.tv_usec = 10000;
404 fdmask = 1 << s;
405 if (select(s + 1, (fd_set *)&fdmask, (fd_set *)NULL,
406 (fd_set *)NULL, &timeout) < 1)
407 continue;
408 }
409 fromlen = sizeof(from);
410 if ((cc = recvfrom(s, (char *)packet, packlen, 0,
411 (struct sockaddr *)&from, &fromlen)) < 0) {
412 if (errno == EINTR)
413 continue;
414 perror("ping: recvfrom");
415 continue;
416 }
417 pr_pack((char *)packet, cc, &from);
418 if (npackets && nreceived >= npackets)
419 break;
420 }
421 finish();
422 /* NOTREACHED */
423 exit(0); /* Make the compiler happy */
424 }
425
426 /*
427 * catcher --
428 * This routine causes another PING to be transmitted, and then
429 * schedules another SIGALRM for 1 second from now.
430 *
431 * bug --
432 * Our sense of time will slowly skew (i.e., packets will not be
433 * launched exactly at 1-second intervals). This does not affect the
434 * quality of the delay and loss statistics.
435 */
436 void
437 catcher()
438 {
439 int waittime;
440
441 pinger();
442 (void)signal(SIGALRM, catcher);
443 if (!npackets || ntransmitted < npackets)
444 alarm((u_int)interval);
445 else {
446 if (nreceived) {
447 waittime = 2 * tmax / 1000;
448 if (!waittime)
449 waittime = 1;
450 } else
451 waittime = maxwait;
452 (void)signal(SIGALRM, finish);
453 (void)alarm((u_int)waittime);
454 }
455 }
456
457 /*
458 * pinger --
459 * Compose and transmit an ICMP ECHO REQUEST packet. The IP packet
460 * will be added on by the kernel. The ID field is our UNIX process ID,
461 * and the sequence number is an ascending integer. The first 8 bytes
462 * of the data portion are used to hold a UNIX "timeval" struct in VAX
463 * byte-order, to compute the round-trip time.
464 */
465 void
466 pinger()
467 {
468 register struct icmp *icp;
469 register int cc;
470 int i;
471
472 icp = (struct icmp *)outpack;
473 icp->icmp_type = ICMP_ECHO;
474 icp->icmp_code = 0;
475 icp->icmp_cksum = 0;
476 icp->icmp_seq = ntransmitted++;
477 icp->icmp_id = ident; /* ID */
478
479 CLR(icp->icmp_seq % mx_dup_ck);
480
481 if (timing)
482 (void)gettimeofday((struct timeval *)&outpack[8],
483 (struct timezone *)NULL);
484
485 cc = datalen + 8; /* skips ICMP portion */
486
487 /* compute ICMP checksum here */
488 icp->icmp_cksum = in_cksum((u_short *)icp, cc);
489
490 i = sendto(s, (char *)outpack, cc, 0, &whereto,
491 sizeof(struct sockaddr));
492
493 if (i < 0 || i != cc) {
494 if (i < 0)
495 perror("ping: sendto");
496 (void)printf("ping: wrote %s %d chars, ret=%d\n",
497 hostname, cc, i);
498 }
499 if (!(options & F_QUIET) && options & F_FLOOD)
500 (void)write(STDOUT_FILENO, &DOT, 1);
501 }
502
503 /*
504 * pr_pack --
505 * Print out the packet, if it came from us. This logic is necessary
506 * because ALL readers of the ICMP socket get a copy of ALL ICMP packets
507 * which arrive ('tis only fair). This permits multiple copies of this
508 * program to be run without having intermingled output (or statistics!).
509 */
510 void
511 pr_pack(buf, cc, from)
512 char *buf;
513 int cc;
514 struct sockaddr_in *from;
515 {
516 register struct icmp *icp;
517 register u_long l;
518 register int i, j;
519 register u_char *cp,*dp;
520 static int old_rrlen;
521 static char old_rr[MAX_IPOPTLEN];
522 struct ip *ip;
523 struct timeval tv, tp;
524 char *pkttime;
525 double triptime;
526 int hlen, dupflag;
527
528 (void)gettimeofday(&tv, (struct timezone *)NULL);
529
530 /* Check the IP header */
531 ip = (struct ip *)buf;
532 hlen = ip->ip_hl << 2;
533 if (cc < hlen + ICMP_MINLEN) {
534 if (options & F_VERBOSE)
535 warnx("packet too short (%d bytes) from %s", cc,
536 inet_ntoa(*(struct in_addr *)&from->sin_addr.s_addr));
537 return;
538 }
539
540 /* Now the ICMP part */
541 cc -= hlen;
542 icp = (struct icmp *)(buf + hlen);
543 if (icp->icmp_type == ICMP_ECHOREPLY) {
544 if (icp->icmp_id != ident)
545 return; /* 'Twas not our ECHO */
546 ++nreceived;
547 if (timing) {
548 #ifndef icmp_data
549 pkttime = (char *)&icp->icmp_ip;
550 #else
551 pkttime = (char *)icp->icmp_data;
552 #endif
553 memcpy(&tp, pkttime, sizeof (tp));
554 timersub(&tv, &tp, &tv);
555 triptime = ((double)tv.tv_sec) * 1000.0 +
556 ((double)tv.tv_usec) / 1000.0;
557 tsum += triptime;
558 if (triptime < tmin)
559 tmin = triptime;
560 if (triptime > tmax)
561 tmax = triptime;
562 }
563
564 if (TST(icp->icmp_seq % mx_dup_ck)) {
565 ++nrepeats;
566 --nreceived;
567 dupflag = 1;
568 } else {
569 SET(icp->icmp_seq % mx_dup_ck);
570 dupflag = 0;
571 }
572
573 if (options & F_QUIET)
574 return;
575
576 if (options & F_FLOOD)
577 (void)write(STDOUT_FILENO, &BSPACE, 1);
578 else {
579 (void)printf("%d bytes from %s: icmp_seq=%u", cc,
580 inet_ntoa(*(struct in_addr *)&from->sin_addr.s_addr),
581 icp->icmp_seq);
582 (void)printf(" ttl=%d", ip->ip_ttl);
583 if (timing)
584 (void)printf(" time=%.3f ms", triptime);
585 if (dupflag)
586 (void)printf(" (DUP!)");
587 /* check the data */
588 cp = (u_char*)&icp->icmp_data[sizeof (struct timeval)];
589 dp = &outpack[8 + sizeof (struct timeval)];
590 for (i = 8 + sizeof(struct timeval); i < datalen;
591 ++i, ++cp, ++dp) {
592 if (*cp != *dp) {
593 (void)printf("\nwrong data byte #%d should be 0x%x but was 0x%x",
594 i, *dp, *cp);
595 cp = (u_char*)&icp->icmp_data[0];
596 for (i = 8; i < datalen; ++i, ++cp) {
597 if ((i % 32) == 8)
598 (void)printf("\n\t");
599 (void)printf("%x ", *cp);
600 }
601 break;
602 }
603 }
604 }
605 } else {
606 /* We've got something other than an ECHOREPLY */
607 if (!(options & F_VERBOSE))
608 return;
609 (void)printf("%d bytes from %s: ", cc,
610 pr_addr(from->sin_addr.s_addr));
611 pr_icmph(icp);
612 }
613
614 /* Display any IP options */
615 cp = (u_char *)buf + sizeof(struct ip);
616
617 for (; hlen > (int)sizeof(struct ip); --hlen, ++cp)
618 switch (*cp) {
619 case IPOPT_EOL:
620 hlen = 0;
621 break;
622 case IPOPT_LSRR:
623 (void)printf("\nLSRR: ");
624 hlen -= 2;
625 j = *++cp;
626 ++cp;
627 if (j > IPOPT_MINOFF)
628 for (;;) {
629 l = *++cp;
630 l = (l<<8) + *++cp;
631 l = (l<<8) + *++cp;
632 l = (l<<8) + *++cp;
633 if (l == 0)
634 (void)printf("\t0.0.0.0");
635 else
636 (void)printf("\t%s", pr_addr(ntohl(l)));
637 hlen -= 4;
638 j -= 4;
639 if (j <= IPOPT_MINOFF)
640 break;
641 (void)putchar('\n');
642 }
643 break;
644 case IPOPT_RR:
645 j = *++cp; /* get length */
646 i = *++cp; /* and pointer */
647 hlen -= 2;
648 if (i > j)
649 i = j;
650 i -= IPOPT_MINOFF;
651 if (i <= 0)
652 continue;
653 if (i == old_rrlen
654 && cp == (u_char *)buf + sizeof(struct ip) + 2
655 && !memcmp(cp, old_rr, i)
656 && !(options & F_FLOOD)) {
657 (void)printf("\t(same route)");
658 i = ((i + 3) / 4) * 4;
659 hlen -= i;
660 cp += i;
661 break;
662 }
663 old_rrlen = i;
664 memcpy(old_rr, cp, i);
665 (void)printf("\nRR: ");
666 for (;;) {
667 l = *++cp;
668 l = (l<<8) + *++cp;
669 l = (l<<8) + *++cp;
670 l = (l<<8) + *++cp;
671 if (l == 0)
672 (void)printf("\t0.0.0.0");
673 else
674 (void)printf("\t%s", pr_addr(ntohl(l)));
675 hlen -= 4;
676 i -= 4;
677 if (i <= 0)
678 break;
679 (void)putchar('\n');
680 }
681 break;
682 case IPOPT_NOP:
683 (void)printf("\nNOP");
684 break;
685 default:
686 (void)printf("\nunknown option %x", *cp);
687 break;
688 }
689 if (!(options & F_FLOOD)) {
690 (void)putchar('\n');
691 (void)fflush(stdout);
692 }
693 }
694
695 /*
696 * in_cksum --
697 * Checksum routine for Internet Protocol family headers (C Version)
698 */
699 int
700 in_cksum(addr, len)
701 u_short *addr;
702 int len;
703 {
704 register int nleft = len;
705 register u_short *w = addr;
706 register int sum = 0;
707 u_short answer = 0;
708
709 /*
710 * Our algorithm is simple, using a 32 bit accumulator (sum), we add
711 * sequential 16 bit words to it, and at the end, fold back all the
712 * carry bits from the top 16 bits into the lower 16 bits.
713 */
714 while (nleft > 1) {
715 sum += *w++;
716 nleft -= 2;
717 }
718
719 /* mop up an odd byte, if necessary */
720 if (nleft == 1) {
721 *(u_char *)(&answer) = *(u_char *)w ;
722 sum += answer;
723 }
724
725 /* add back carry outs from top 16 bits to low 16 bits */
726 sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */
727 sum += (sum >> 16); /* add carry */
728 answer = ~sum; /* truncate to 16 bits */
729 return(answer);
730 }
731
732 /*
733 * pr_stats --
734 * Print out statistics, for statistics() and finish()
735 */
736 void
737 pr_stats()
738 {
739 register int i;
740
741 (void)fflush(stdout);
742 (void)printf("--- %s ping statistics ---\n", hostname);
743 (void)printf("%ld packets transmitted, ", ntransmitted);
744 (void)printf("%ld packets received, ", nreceived);
745 if (nrepeats)
746 (void)printf("+%ld duplicates, ", nrepeats);
747 if (ntransmitted)
748 if (nreceived > ntransmitted)
749 (void)printf("-- somebody's printing up packets!");
750 else
751 (void)printf("%d%% packet loss",
752 (int) (((ntransmitted - nreceived) * 100) /
753 ntransmitted));
754 (void)putchar('\n');
755 if (nreceived && timing) {
756 /* Only display average to microseconds */
757 i = 1000.0 * tsum / (nreceived + nrepeats);
758 (void)printf("round-trip min/avg/max = %.3f/%.3f/%.3f ms\n",
759 tmin, ((double)i) / 1000.0, tmax);
760 }
761 }
762
763 /*
764 * statistics --
765 * Print out statistics when requested by SIGINFO.
766 */
767 void
768 statistics()
769 {
770
771 pr_stats();
772 printf("---\n");
773 }
774
775 /*
776 * finish --
777 * Print out statistics, and give up.
778 */
779 void
780 finish()
781 {
782
783 (void)signal(SIGINFO, SIG_IGN);
784 (void)signal(SIGINT, SIG_IGN);
785
786 (void)putchar('\n');
787 pr_stats();
788
789 exit(nreceived ? 0 : 1);
790 }
791
792 #ifdef notdef
793 static char *ttab[] = {
794 "Echo Reply", /* ip + seq + udata */
795 "Dest Unreachable", /* net, host, proto, port, frag, sr + IP */
796 "Source Quench", /* IP */
797 "Redirect", /* redirect type, gateway, + IP */
798 "Echo",
799 "Time Exceeded", /* transit, frag reassem + IP */
800 "Parameter Problem", /* pointer + IP */
801 "Timestamp", /* id + seq + three timestamps */
802 "Timestamp Reply", /* " */
803 "Info Request", /* id + sq */
804 "Info Reply" /* " */
805 };
806 #endif
807
808 /*
809 * pr_icmph --
810 * Print a descriptive string about an ICMP header.
811 */
812 void
813 pr_icmph(icp)
814 struct icmp *icp;
815 {
816 switch(icp->icmp_type) {
817 case ICMP_ECHOREPLY:
818 (void)printf("Echo Reply\n");
819 /* XXX ID + Seq + Data */
820 break;
821 case ICMP_UNREACH:
822 switch(icp->icmp_code) {
823 case ICMP_UNREACH_NET:
824 (void)printf("Destination Net Unreachable\n");
825 break;
826 case ICMP_UNREACH_HOST:
827 (void)printf("Destination Host Unreachable\n");
828 break;
829 case ICMP_UNREACH_PROTOCOL:
830 (void)printf("Destination Protocol Unreachable\n");
831 break;
832 case ICMP_UNREACH_PORT:
833 (void)printf("Destination Port Unreachable\n");
834 break;
835 case ICMP_UNREACH_NEEDFRAG:
836 (void)printf("frag needed and DF set\n");
837 break;
838 case ICMP_UNREACH_SRCFAIL:
839 (void)printf("Source Route Failed\n");
840 break;
841 default:
842 (void)printf("Dest Unreachable, Bad Code: %d\n",
843 icp->icmp_code);
844 break;
845 }
846 /* Print returned IP header information */
847 #ifndef icmp_data
848 pr_retip(&icp->icmp_ip);
849 #else
850 pr_retip((struct ip *)icp->icmp_data);
851 #endif
852 break;
853 case ICMP_SOURCEQUENCH:
854 (void)printf("Source Quench\n");
855 #ifndef icmp_data
856 pr_retip(&icp->icmp_ip);
857 #else
858 pr_retip((struct ip *)icp->icmp_data);
859 #endif
860 break;
861 case ICMP_REDIRECT:
862 switch(icp->icmp_code) {
863 case ICMP_REDIRECT_NET:
864 (void)printf("Redirect Network");
865 break;
866 case ICMP_REDIRECT_HOST:
867 (void)printf("Redirect Host");
868 break;
869 case ICMP_REDIRECT_TOSNET:
870 (void)printf("Redirect Type of Service and Network");
871 break;
872 case ICMP_REDIRECT_TOSHOST:
873 (void)printf("Redirect Type of Service and Host");
874 break;
875 default:
876 (void)printf("Redirect, Bad Code: %d", icp->icmp_code);
877 break;
878 }
879 (void)printf("(New addr: 0x%08lx)\n",
880 (u_long)icp->icmp_gwaddr.s_addr);
881 #ifndef icmp_data
882 pr_retip(&icp->icmp_ip);
883 #else
884 pr_retip((struct ip *)icp->icmp_data);
885 #endif
886 break;
887 case ICMP_ECHO:
888 (void)printf("Echo Request\n");
889 /* XXX ID + Seq + Data */
890 break;
891 case ICMP_TIMXCEED:
892 switch(icp->icmp_code) {
893 case ICMP_TIMXCEED_INTRANS:
894 (void)printf("Time to live exceeded\n");
895 break;
896 case ICMP_TIMXCEED_REASS:
897 (void)printf("Frag reassembly time exceeded\n");
898 break;
899 default:
900 (void)printf("Time exceeded, Bad Code: %d\n",
901 icp->icmp_code);
902 break;
903 }
904 #ifndef icmp_data
905 pr_retip(&icp->icmp_ip);
906 #else
907 pr_retip((struct ip *)icp->icmp_data);
908 #endif
909 break;
910 case ICMP_PARAMPROB:
911 (void)printf("Parameter problem: pointer = 0x%02x\n",
912 icp->icmp_hun.ih_pptr);
913 #ifndef icmp_data
914 pr_retip(&icp->icmp_ip);
915 #else
916 pr_retip((struct ip *)icp->icmp_data);
917 #endif
918 break;
919 case ICMP_TSTAMP:
920 (void)printf("Timestamp\n");
921 /* XXX ID + Seq + 3 timestamps */
922 break;
923 case ICMP_TSTAMPREPLY:
924 (void)printf("Timestamp Reply\n");
925 /* XXX ID + Seq + 3 timestamps */
926 break;
927 case ICMP_IREQ:
928 (void)printf("Information Request\n");
929 /* XXX ID + Seq */
930 break;
931 case ICMP_IREQREPLY:
932 (void)printf("Information Reply\n");
933 /* XXX ID + Seq */
934 break;
935 #ifdef ICMP_MASKREQ
936 case ICMP_MASKREQ:
937 (void)printf("Address Mask Request\n");
938 break;
939 #endif
940 #ifdef ICMP_MASKREPLY
941 case ICMP_MASKREPLY:
942 (void)printf("Address Mask Reply\n");
943 break;
944 #endif
945 default:
946 (void)printf("Bad ICMP type: %d\n", icp->icmp_type);
947 }
948 }
949
950 /*
951 * pr_iph --
952 * Print an IP header with options.
953 */
954 void
955 pr_iph(ip)
956 struct ip *ip;
957 {
958 int hlen;
959 u_char *cp;
960
961 hlen = ip->ip_hl << 2;
962 cp = (u_char *)ip + 20; /* point to options */
963
964 (void)printf("Vr HL TOS Len ID Flg off TTL Pro cks Src Dst Data\n");
965 (void)printf(" %1x %1x %02x %04x %04x",
966 ip->ip_v, ip->ip_hl, ip->ip_tos, ip->ip_len, ip->ip_id);
967 (void)printf(" %1x %04x", ((ip->ip_off) & 0xe000) >> 13,
968 (ip->ip_off) & 0x1fff);
969 (void)printf(" %02x %02x %04x", ip->ip_ttl, ip->ip_p, ip->ip_sum);
970 (void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_src.s_addr));
971 (void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_dst.s_addr));
972 /* dump and option bytes */
973 while (hlen-- > 20) {
974 (void)printf("%02x", *cp++);
975 }
976 (void)putchar('\n');
977 }
978
979 /*
980 * pr_addr --
981 * Return an ascii host address as a dotted quad and optionally with
982 * a hostname.
983 */
984 char *
985 pr_addr(l)
986 u_long l;
987 {
988 struct hostent *hp;
989 static char buf[80];
990
991 if ((options & F_NUMERIC) ||
992 !(hp = gethostbyaddr((char *)&l, 4, AF_INET)))
993 (void)sprintf(buf, "%s", inet_ntoa(*(struct in_addr *)&l));
994 else
995 (void)sprintf(buf, "%s (%s)", hp->h_name,
996 inet_ntoa(*(struct in_addr *)&l));
997 return(buf);
998 }
999
1000 /*
1001 * pr_retip --
1002 * Dump some info on a returned (via ICMP) IP packet.
1003 */
1004 void
1005 pr_retip(ip)
1006 struct ip *ip;
1007 {
1008 int hlen;
1009 u_char *cp;
1010
1011 pr_iph(ip);
1012 hlen = ip->ip_hl << 2;
1013 cp = (u_char *)ip + hlen;
1014
1015 if (ip->ip_p == 6)
1016 (void)printf("TCP: from port %u, to port %u (decimal)\n",
1017 (*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3)));
1018 else if (ip->ip_p == 17)
1019 (void)printf("UDP: from port %u, to port %u (decimal)\n",
1020 (*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3)));
1021 }
1022
1023 void
1024 fill(bp, patp)
1025 char *bp, *patp;
1026 {
1027 register int ii, jj, kk;
1028 int pat[16];
1029 char *cp;
1030
1031 for (cp = patp; *cp; cp++)
1032 if (!isxdigit(*cp))
1033 errx(1, "patterns must be specified as hex digits");
1034 ii = sscanf(patp,
1035 "%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x",
1036 &pat[0], &pat[1], &pat[2], &pat[3], &pat[4], &pat[5], &pat[6],
1037 &pat[7], &pat[8], &pat[9], &pat[10], &pat[11], &pat[12],
1038 &pat[13], &pat[14], &pat[15]);
1039
1040 if (ii > 0)
1041 for (kk = 0;
1042 kk <= MAXPACKET - (8 + sizeof(struct timeval) + ii);
1043 kk += ii)
1044 for (jj = 0; jj < ii; ++jj)
1045 bp[jj + kk] = pat[jj];
1046 if (!(options & F_QUIET)) {
1047 (void)printf("PATTERN: 0x");
1048 for (jj = 0; jj < ii; ++jj)
1049 (void)printf("%02x", bp[jj] & 0xFF);
1050 (void)printf("\n");
1051 }
1052 }
1053
1054 void
1055 usage()
1056 {
1057 (void)fprintf(stderr,
1058 "usage: ping [-dfLnqRrv] [-c count] [-I ifaddr] [ -S ifaddr ] [-i wait]\n\t[-l preload] [-p pattern] [-s packetsize] [-t ttl] [-w maxwait] host\n");
1059 exit(1);
1060 }
1061