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