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