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