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