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