ping.c revision 34995
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 38static const 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/* 45static char sccsid[] = "@(#)ping.c 8.1 (Berkeley) 6/5/93"; 46*/ 47static const char rcsid[] = 48 "$Id: ping.c,v 1.30 1998/04/01 00:32:18 imp Exp $"; 49#endif /* not lint */ 50 51/* 52 * P I N G . C 53 * 54 * Using the InterNet Control Message Protocol (ICMP) "ECHO" facility, 55 * measure round-trip-delays and packet loss across network paths. 56 * 57 * Author - 58 * Mike Muuss 59 * U. S. Army Ballistic Research Laboratory 60 * December, 1983 61 * 62 * Status - 63 * Public Domain. Distribution Unlimited. 64 * Bugs - 65 * More statistics could always be gathered. 66 * This program has to run SUID to ROOT to access the ICMP socket. 67 */ 68 69#include <sys/param.h> /* NB: we rely on this for <sys/types.h> */ 70 71#include <ctype.h> 72#include <err.h> 73#include <errno.h> 74#include <math.h> 75#include <netdb.h> 76#include <signal.h> 77#include <stdio.h> 78#include <stdlib.h> 79#include <string.h> 80#include <sysexits.h> 81#include <termios.h> 82#include <unistd.h> 83 84#include <sys/socket.h> 85#include <sys/file.h> 86#include <sys/time.h> 87 88#include <netinet/in.h> 89#include <netinet/in_systm.h> 90#include <netinet/ip.h> 91#include <netinet/ip_icmp.h> 92#include <netinet/ip_var.h> 93#include <arpa/inet.h> 94 95#define DEFDATALEN (64 - 8) /* default data length */ 96#define FLOOD_BACKOFF 20000 /* usecs to back off if F_FLOOD mode */ 97 /* runs out of buffer space */ 98#define MAXIPLEN 60 99#define MAXICMPLEN 76 100#define MAXPACKET (65536 - 60 - 8)/* max packet size */ 101#define MAXWAIT 10 /* max seconds to wait for response */ 102#define NROUTES 9 /* number of record route slots */ 103 104#define A(bit) rcvd_tbl[(bit)>>3] /* identify byte in array */ 105#define B(bit) (1 << ((bit) & 0x07)) /* identify bit in byte */ 106#define SET(bit) (A(bit) |= B(bit)) 107#define CLR(bit) (A(bit) &= (~B(bit))) 108#define TST(bit) (A(bit) & B(bit)) 109 110/* various options */ 111int options; 112#define F_FLOOD 0x0001 113#define F_INTERVAL 0x0002 114#define F_NUMERIC 0x0004 115#define F_PINGFILLED 0x0008 116#define F_QUIET 0x0010 117#define F_RROUTE 0x0020 118#define F_SO_DEBUG 0x0040 119#define F_SO_DONTROUTE 0x0080 120#define F_VERBOSE 0x0100 121#define F_QUIET2 0x0200 122#define F_NOLOOP 0x0400 123#define F_MTTL 0x0800 124#define F_MIF 0x1000 125#define F_AUDIBLE 0x2000 126 127/* 128 * MAX_DUP_CHK is the number of bits in received table, i.e. the maximum 129 * number of received sequence numbers we can keep track of. Change 128 130 * to 8192 for complete accuracy... 131 */ 132#define MAX_DUP_CHK (8 * 128) 133int mx_dup_ck = MAX_DUP_CHK; 134char rcvd_tbl[MAX_DUP_CHK / 8]; 135 136struct sockaddr whereto; /* who to ping */ 137int datalen = DEFDATALEN; 138int s; /* socket file descriptor */ 139u_char outpack[MAXPACKET]; 140char BSPACE = '\b'; /* characters written for flood */ 141char DOT = '.'; 142char *hostname; 143int ident; /* process id to identify our packets */ 144int uid; /* cached uid for micro-optimization */ 145 146/* counters */ 147long npackets; /* max packets to transmit */ 148long nreceived; /* # of packets we got back */ 149long nrepeats; /* number of duplicates */ 150long ntransmitted; /* sequence # for outbound packets = #sent */ 151int interval = 1; /* interval between packets */ 152 153/* timing */ 154int timing; /* flag to do timing */ 155double tmin = 999999999.0; /* minimum round trip time */ 156double tmax = 0.0; /* maximum round trip time */ 157double tsum = 0.0; /* sum of all times, for doing average */ 158double tsumsq = 0.0; /* sum of all times squared, for std. dev. */ 159 160volatile sig_atomic_t finish_up; /* nonzero if we've been told to finish up */ 161int reset_kerninfo; 162volatile sig_atomic_t siginfo_p; 163 164static void fill(char *, char *); 165static u_short in_cksum(u_short *, int); 166static void catcher(int sig); 167static void check_status(void); 168static void finish(void) __dead2; 169static void pinger(void); 170static char *pr_addr(struct in_addr); 171static void pr_icmph(struct icmp *); 172static void pr_iph(struct ip *); 173static void pr_pack(char *, int, struct sockaddr_in *); 174static void pr_retip(struct ip *); 175static void status(int); 176static void stopit(int); 177static void tvsub(struct timeval *, struct timeval *); 178static void usage(const char *) __dead2; 179 180int 181main(argc, argv) 182 int argc; 183 char *const *argv; 184{ 185 struct timeval timeout; 186 struct hostent *hp; 187 struct sockaddr_in *to; 188 struct termios ts; 189 register int i; 190 int ch, fdmask, hold, packlen, preload, sockerrno; 191 struct in_addr ifaddr; 192 unsigned char ttl, loop; 193 u_char *datap, *packet; 194 char *target, hnamebuf[MAXHOSTNAMELEN]; 195 char *ep; 196 u_long ultmp; 197#ifdef IP_OPTIONS 198 char rspace[3 + 4 * NROUTES + 1]; /* record route space */ 199#endif 200 struct sigaction si_sa; 201 202 /* 203 * Do the stuff that we need root priv's for *first*, and 204 * then drop our setuid bit. Save error reporting for 205 * after arg parsing. 206 */ 207 s = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP); 208 sockerrno = errno; 209 210 setuid(getuid()); 211 uid = getuid(); 212 213 preload = 0; 214 215 datap = &outpack[8 + sizeof(struct timeval)]; 216 while ((ch = getopt(argc, argv, "I:LQRT:c:adfi:l:np:qrs:v")) != -1) { 217 switch(ch) { 218 case 'a': 219 options |= F_AUDIBLE; 220 break; 221 case 'c': 222 ultmp = strtoul(optarg, &ep, 0); 223 if (*ep || ep == optarg || ultmp > LONG_MAX || !ultmp) 224 errx(EX_USAGE, 225 "invalid count of packets to transmit: `%s'", 226 optarg); 227 npackets = ultmp; 228 break; 229 case 'd': 230 options |= F_SO_DEBUG; 231 break; 232 case 'f': 233 if (getuid()) { 234 errno = EPERM; 235 err(EX_NOPERM, "-f flag"); 236 } 237 options |= F_FLOOD; 238 setbuf(stdout, (char *)NULL); 239 break; 240 case 'i': /* wait between sending packets */ 241 ultmp = strtoul(optarg, &ep, 0); 242 if (*ep || ep == optarg || ultmp > INT_MAX) 243 errx(EX_USAGE, 244 "invalid timing interval: `%s'", optarg); 245 options |= F_INTERVAL; 246 interval = ultmp; 247 break; 248 case 'I': /* multicast interface */ 249 if (inet_aton(optarg, &ifaddr) == 0) 250 errx(EX_USAGE, 251 "invalid multicast interface: `%s'", 252 optarg); 253 options |= F_MIF; 254 break; 255 case 'l': 256 ultmp = strtoul(optarg, &ep, 0); 257 if (*ep || ep == optarg || ultmp > INT_MAX) 258 errx(EX_USAGE, 259 "invalid preload value: `%s'", optarg); 260 if (getuid()) { 261 errno = EPERM; 262 err(EX_NOPERM, "-l flag"); 263 } 264 preload = ultmp; 265 break; 266 case 'L': 267 options |= F_NOLOOP; 268 loop = 0; 269 break; 270 case 'n': 271 options |= F_NUMERIC; 272 break; 273 case 'p': /* fill buffer with user pattern */ 274 options |= F_PINGFILLED; 275 fill((char *)datap, optarg); 276 break; 277 case 'Q': 278 options |= F_QUIET2; 279 break; 280 case 'q': 281 options |= F_QUIET; 282 break; 283 case 'R': 284 options |= F_RROUTE; 285 break; 286 case 'r': 287 options |= F_SO_DONTROUTE; 288 break; 289 case 's': /* size of packet to send */ 290 ultmp = strtoul(optarg, &ep, 0); 291 if (ultmp > MAXPACKET) 292 errx(EX_USAGE, "packet size too large: %lu", 293 ultmp); 294 if (*ep || ep == optarg || !ultmp) 295 errx(EX_USAGE, "invalid packet size: `%s'", 296 optarg); 297 datalen = ultmp; 298 break; 299 case 'T': /* multicast TTL */ 300 ultmp = strtoul(optarg, &ep, 0); 301 if (*ep || ep == optarg || ultmp > 255) 302 errx(EX_USAGE, "invalid multicast TTL: `%s'", 303 optarg); 304 ttl = ultmp; 305 options |= F_MTTL; 306 break; 307 case 'v': 308 options |= F_VERBOSE; 309 break; 310 default: 311 312 usage(argv[0]); 313 } 314 } 315 316 if (argc - optind != 1) 317 usage(argv[0]); 318 target = argv[optind]; 319 320 bzero((char *)&whereto, sizeof(struct sockaddr)); 321 to = (struct sockaddr_in *)&whereto; 322 to->sin_family = AF_INET; 323 if (inet_aton(target, &to->sin_addr) != 0) { 324 hostname = target; 325 } else { 326 hp = gethostbyname2(target, AF_INET); 327 if (!hp) 328 errx(EX_NOHOST, "cannot resolve %s: %s", 329 target, hstrerror(h_errno)); 330 331 to->sin_len = sizeof *to; 332 if (hp->h_length > sizeof(to->sin_addr)) 333 errx(1,"gethostbyname2 returned an illegal address"); 334 memcpy(&to->sin_addr, hp->h_addr_list[0], sizeof to->sin_addr); 335 (void)strncpy(hnamebuf, hp->h_name, sizeof(hnamebuf) - 1); 336 hnamebuf[sizeof(hnamebuf) - 1] = '\0'; 337 hostname = hnamebuf; 338 } 339 340 if (options & F_FLOOD && options & F_INTERVAL) 341 errx(EX_USAGE, "-f and -i: incompatible options"); 342 343 if (options & F_FLOOD && IN_MULTICAST(ntohl(to->sin_addr.s_addr))) 344 errx(EX_USAGE, 345 "-f flag cannot be used with multicast destination"); 346 if (options & (F_MIF | F_NOLOOP | F_MTTL) 347 && !IN_MULTICAST(ntohl(to->sin_addr.s_addr))) 348 errx(EX_USAGE, 349 "-I, -L, -T flags cannot be used with unicast destination"); 350 351 if (datalen >= sizeof(struct timeval)) /* can we time transfer */ 352 timing = 1; 353 packlen = datalen + MAXIPLEN + MAXICMPLEN; 354 if (!(packet = (u_char *)malloc((size_t)packlen))) 355 err(EX_UNAVAILABLE, "malloc"); 356 357 if (!(options & F_PINGFILLED)) 358 for (i = 8; i < datalen; ++i) 359 *datap++ = i; 360 361 ident = getpid() & 0xFFFF; 362 363 if (s < 0) { 364 errno = sockerrno; 365 err(EX_OSERR, "socket"); 366 } 367 hold = 1; 368 if (options & F_SO_DEBUG) 369 (void)setsockopt(s, SOL_SOCKET, SO_DEBUG, (char *)&hold, 370 sizeof(hold)); 371 if (options & F_SO_DONTROUTE) 372 (void)setsockopt(s, SOL_SOCKET, SO_DONTROUTE, (char *)&hold, 373 sizeof(hold)); 374 375 /* record route option */ 376 if (options & F_RROUTE) { 377#ifdef IP_OPTIONS 378 rspace[IPOPT_OPTVAL] = IPOPT_RR; 379 rspace[IPOPT_OLEN] = sizeof(rspace)-1; 380 rspace[IPOPT_OFFSET] = IPOPT_MINOFF; 381 if (setsockopt(s, IPPROTO_IP, IP_OPTIONS, rspace, 382 sizeof(rspace)) < 0) 383 err(EX_OSERR, "setsockopt IP_OPTIONS"); 384#else 385 errx(EX_UNAVAILABLE, 386 "record route not available in this implementation"); 387#endif /* IP_OPTIONS */ 388 } 389 390 if (options & F_NOLOOP) { 391 if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_LOOP, &loop, 392 sizeof(loop)) < 0) { 393 err(EX_OSERR, "setsockopt IP_MULTICAST_LOOP"); 394 } 395 } 396 if (options & F_MTTL) { 397 if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, 398 sizeof(ttl)) < 0) { 399 err(EX_OSERR, "setsockopt IP_MULTICAST_TTL"); 400 } 401 } 402 if (options & F_MIF) { 403 if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_IF, &ifaddr, 404 sizeof(ifaddr)) < 0) { 405 err(EX_OSERR, "setsockopt IP_MULTICAST_IF"); 406 } 407 } 408 409 /* 410 * When pinging the broadcast address, you can get a lot of answers. 411 * Doing something so evil is useful if you are trying to stress the 412 * ethernet, or just want to fill the arp cache to get some stuff for 413 * /etc/ethers. But beware: RFC 1122 allows hosts to ignore broadcast 414 * or multicast pings if they wish. 415 */ 416 hold = 48 * 1024; 417 (void)setsockopt(s, SOL_SOCKET, SO_RCVBUF, (char *)&hold, 418 sizeof(hold)); 419 420 if (to->sin_family == AF_INET) 421 (void)printf("PING %s (%s): %d data bytes\n", hostname, 422 inet_ntoa(to->sin_addr), 423 datalen); 424 else 425 (void)printf("PING %s: %d data bytes\n", hostname, datalen); 426 427 /* 428 * Use sigaction() instead of signal() to get unambiguous semantics, 429 * in particular with SA_RESTART not set. 430 */ 431 432 sigemptyset(&si_sa.sa_mask); 433 si_sa.sa_flags = 0; 434 435 si_sa.sa_handler = stopit; 436 if (sigaction(SIGINT, &si_sa, 0) == -1) { 437 err(EX_OSERR, "sigaction SIGINT"); 438 } 439 440 si_sa.sa_handler = catcher; 441 if (sigaction(SIGALRM, &si_sa, 0) == -1) { 442 err(EX_OSERR, "sigaction SIGALRM"); 443 } 444 445 si_sa.sa_handler = status; 446 if (sigaction(SIGINFO, &si_sa, 0) == -1) { 447 err(EX_OSERR, "sigaction"); 448 } 449 450 if (tcgetattr(STDOUT_FILENO, &ts) != -1) { 451 reset_kerninfo = !(ts.c_lflag & NOKERNINFO); 452 ts.c_lflag |= NOKERNINFO; 453 tcsetattr(STDOUT_FILENO, TCSANOW, &ts); 454 } 455 456 while (preload--) /* fire off them quickies */ 457 pinger(); 458 459 if ((options & F_FLOOD) == 0) 460 catcher(0); /* start things going */ 461 462 while (!finish_up) { 463 struct sockaddr_in from; 464 register int cc; 465 int fromlen; 466 467 check_status(); 468 if (options & F_FLOOD) { 469 pinger(); 470 timeout.tv_sec = 0; 471 timeout.tv_usec = 10000; 472 fdmask = 1 << s; 473 if (select(s + 1, (fd_set *)&fdmask, (fd_set *)NULL, 474 (fd_set *)NULL, &timeout) < 1) 475 continue; 476 } 477 fromlen = sizeof(from); 478 if ((cc = recvfrom(s, (char *)packet, packlen, 0, 479 (struct sockaddr *)&from, &fromlen)) < 0) { 480 if (errno == EINTR) 481 continue; 482 perror("ping: recvfrom"); 483 continue; 484 } 485 pr_pack((char *)packet, cc, &from); 486 if (npackets && nreceived >= npackets) 487 break; 488 } 489 finish(); 490 /* NOTREACHED */ 491 exit(0); /* Make the compiler happy */ 492} 493 494/* 495 * stopit -- 496 * Set the global bit that causes the main loop to quit. 497 * Do NOT call finish() from here, since finish() does far too much 498 * to be called from a signal handler. 499 */ 500void 501stopit(sig) 502 int sig; 503{ 504 finish_up = 1; 505} 506 507/* 508 * catcher -- 509 * This routine causes another PING to be transmitted, and then 510 * schedules another SIGALRM for 1 second from now. 511 * 512 * bug -- 513 * Our sense of time will slowly skew (i.e., packets will not be 514 * launched exactly at 1-second intervals). This does not affect the 515 * quality of the delay and loss statistics. 516 */ 517static void 518catcher(int sig) 519{ 520 int waittime; 521 struct sigaction si_sa; 522 523 pinger(); 524 525 if (!npackets || ntransmitted < npackets) 526 (void)alarm((u_int)interval); 527 else { 528 if (nreceived) { 529 waittime = 2 * tmax / 1000; 530 if (!waittime) 531 waittime = 1; 532 } else 533 waittime = MAXWAIT; 534 535 si_sa.sa_handler = stopit; 536 sigemptyset(&si_sa.sa_mask); 537 si_sa.sa_flags = 0; 538 if (sigaction(SIGALRM, &si_sa, 0) == -1) { 539 finish_up = 1; 540 return; 541 } 542 (void)alarm((u_int)waittime); 543 } 544} 545 546/* 547 * pinger -- 548 * Compose and transmit an ICMP ECHO REQUEST packet. The IP packet 549 * will be added on by the kernel. The ID field is our UNIX process ID, 550 * and the sequence number is an ascending integer. The first 8 bytes 551 * of the data portion are used to hold a UNIX "timeval" struct in host 552 * byte-order, to compute the round-trip time. 553 * 554 * bug -- 555 * this does far too much to be called from a signal handler. 556 */ 557static void 558pinger(void) 559{ 560 register struct icmp *icp; 561 register int cc; 562 int i; 563 564 icp = (struct icmp *)outpack; 565 icp->icmp_type = ICMP_ECHO; 566 icp->icmp_code = 0; 567 icp->icmp_cksum = 0; 568 icp->icmp_seq = ntransmitted; 569 icp->icmp_id = ident; /* ID */ 570 571 CLR(icp->icmp_seq % mx_dup_ck); 572 573 if (timing) 574 (void)gettimeofday((struct timeval *)&outpack[8], 575 (struct timezone *)NULL); 576 577 cc = datalen + 8; /* skips ICMP portion */ 578 579 /* compute ICMP checksum here */ 580 icp->icmp_cksum = in_cksum((u_short *)icp, cc); 581 582 i = sendto(s, (char *)outpack, cc, 0, &whereto, 583 sizeof(struct sockaddr)); 584 585 if (i < 0 || i != cc) { 586 if (i < 0) { 587 if (options & F_FLOOD && errno == ENOBUFS) { 588 usleep(FLOOD_BACKOFF); 589 return; 590 } 591 warn("sendto"); 592 } else { 593 warn("%s: partial write: %d of %d bytes", 594 hostname, cc, i); 595 } 596 } 597 ntransmitted++; 598 if (!(options & F_QUIET) && options & F_FLOOD) 599 (void)write(STDOUT_FILENO, &DOT, 1); 600} 601 602/* 603 * pr_pack -- 604 * Print out the packet, if it came from us. This logic is necessary 605 * because ALL readers of the ICMP socket get a copy of ALL ICMP packets 606 * which arrive ('tis only fair). This permits multiple copies of this 607 * program to be run without having intermingled output (or statistics!). 608 */ 609static void 610pr_pack(buf, cc, from) 611 char *buf; 612 int cc; 613 struct sockaddr_in *from; 614{ 615 register struct icmp *icp; 616 register u_long l; 617 register int i, j; 618 register u_char *cp,*dp; 619 static int old_rrlen; 620 static char old_rr[MAX_IPOPTLEN]; 621 struct ip *ip; 622 struct timeval tv, *tp; 623 double triptime; 624 int hlen, dupflag; 625 626 (void)gettimeofday(&tv, (struct timezone *)NULL); 627 628 /* Check the IP header */ 629 ip = (struct ip *)buf; 630 hlen = ip->ip_hl << 2; 631 if (cc < hlen + ICMP_MINLEN) { 632 if (options & F_VERBOSE) 633 warn("packet too short (%d bytes) from %s", cc, 634 inet_ntoa(from->sin_addr)); 635 return; 636 } 637 638 /* Now the ICMP part */ 639 cc -= hlen; 640 icp = (struct icmp *)(buf + hlen); 641 if (icp->icmp_type == ICMP_ECHOREPLY) { 642 if (icp->icmp_id != ident) 643 return; /* 'Twas not our ECHO */ 644 ++nreceived; 645 triptime = 0.0; 646 if (timing) { 647#ifndef icmp_data 648 tp = (struct timeval *)&icp->icmp_ip; 649#else 650 tp = (struct timeval *)icp->icmp_data; 651#endif 652 tvsub(&tv, tp); 653 triptime = ((double)tv.tv_sec) * 1000.0 + 654 ((double)tv.tv_usec) / 1000.0; 655 tsum += triptime; 656 tsumsq += triptime * triptime; 657 if (triptime < tmin) 658 tmin = triptime; 659 if (triptime > tmax) 660 tmax = triptime; 661 } 662 663 if (TST(icp->icmp_seq % mx_dup_ck)) { 664 ++nrepeats; 665 --nreceived; 666 dupflag = 1; 667 } else { 668 SET(icp->icmp_seq % mx_dup_ck); 669 dupflag = 0; 670 } 671 672 if (options & F_QUIET) 673 return; 674 675 if (options & F_FLOOD) 676 (void)write(STDOUT_FILENO, &BSPACE, 1); 677 else { 678 (void)printf("%d bytes from %s: icmp_seq=%u", cc, 679 inet_ntoa(*(struct in_addr *)&from->sin_addr.s_addr), 680 icp->icmp_seq); 681 (void)printf(" ttl=%d", ip->ip_ttl); 682 if (timing) 683 (void)printf(" time=%.3f ms", triptime); 684 if (dupflag) 685 (void)printf(" (DUP!)"); 686 if (options & F_AUDIBLE) 687 (void)printf("\a"); 688 /* check the data */ 689 cp = (u_char*)&icp->icmp_data[8]; 690 dp = &outpack[8 + sizeof(struct timeval)]; 691 for (i = 8; i < datalen; ++i, ++cp, ++dp) { 692 if (*cp != *dp) { 693 (void)printf("\nwrong data byte #%d should be 0x%x but was 0x%x", 694 i, *dp, *cp); 695 cp = (u_char*)&icp->icmp_data[0]; 696 for (i = 8; i < datalen; ++i, ++cp) { 697 if ((i % 32) == 8) 698 (void)printf("\n\t"); 699 (void)printf("%x ", *cp); 700 } 701 break; 702 } 703 } 704 } 705 } else { 706 /* 707 * We've got something other than an ECHOREPLY. 708 * See if it's a reply to something that we sent. 709 * We can compare IP destination, protocol, 710 * and ICMP type and ID. 711 * 712 * Only print all the error messages if we are running 713 * as root to avoid leaking information not normally 714 * available to those not running as root. 715 */ 716#ifndef icmp_data 717 struct ip *oip = &icp->icmp_ip; 718#else 719 struct ip *oip = (struct ip *)icp->icmp_data; 720#endif 721 struct icmp *oicmp = (struct icmp *)(oip + 1); 722 723 if (((options & F_VERBOSE) && uid == 0) || 724 (!(options & F_QUIET2) && 725 (oip->ip_dst.s_addr == 726 ((struct sockaddr_in *)&whereto)->sin_addr.s_addr) && 727 (oip->ip_p == IPPROTO_ICMP) && 728 (oicmp->icmp_type == ICMP_ECHO) && 729 (oicmp->icmp_id == ident))) { 730 (void)printf("%d bytes from %s: ", cc, 731 pr_addr(from->sin_addr)); 732 pr_icmph(icp); 733 } else 734 return; 735 } 736 737 /* Display any IP options */ 738 cp = (u_char *)buf + sizeof(struct ip); 739 740 for (; hlen > (int)sizeof(struct ip); --hlen, ++cp) 741 switch (*cp) { 742 case IPOPT_EOL: 743 hlen = 0; 744 break; 745 case IPOPT_LSRR: 746 (void)printf("\nLSRR: "); 747 hlen -= 2; 748 j = *++cp; 749 ++cp; 750 if (j > IPOPT_MINOFF) 751 for (;;) { 752 l = *++cp; 753 l = (l<<8) + *++cp; 754 l = (l<<8) + *++cp; 755 l = (l<<8) + *++cp; 756 if (l == 0) { 757 printf("\t0.0.0.0"); 758 } else { 759 struct in_addr ina; 760 ina.s_addr = ntohl(l); 761 printf("\t%s", pr_addr(ina)); 762 } 763 hlen -= 4; 764 j -= 4; 765 if (j <= IPOPT_MINOFF) 766 break; 767 (void)putchar('\n'); 768 } 769 break; 770 case IPOPT_RR: 771 j = *++cp; /* get length */ 772 i = *++cp; /* and pointer */ 773 hlen -= 2; 774 if (i > j) 775 i = j; 776 i -= IPOPT_MINOFF; 777 if (i <= 0) 778 continue; 779 if (i == old_rrlen 780 && cp == (u_char *)buf + sizeof(struct ip) + 2 781 && !bcmp((char *)cp, old_rr, i) 782 && !(options & F_FLOOD)) { 783 (void)printf("\t(same route)"); 784 i = ((i + 3) / 4) * 4; 785 hlen -= i; 786 cp += i; 787 break; 788 } 789 if (i < MAX_IPOPTLEN) { 790 old_rrlen = i; 791 bcopy((char *)cp, old_rr, i); 792 } else 793 old_rrlen = 0; 794 795 (void)printf("\nRR: "); 796 j = 0; 797 for (;;) { 798 l = *++cp; 799 l = (l<<8) + *++cp; 800 l = (l<<8) + *++cp; 801 l = (l<<8) + *++cp; 802 if (l == 0) { 803 printf("\t0.0.0.0"); 804 } else { 805 struct in_addr ina; 806 ina.s_addr = ntohl(l); 807 printf("\t%s", pr_addr(ina)); 808 } 809 hlen -= 4; 810 i -= 4; 811 j += 4; 812 if (i <= 0) 813 break; 814 if (j >= MAX_IPOPTLEN) { 815 (void) printf("\t(truncated route)"); 816 break; 817 } 818 (void)putchar('\n'); 819 } 820 break; 821 case IPOPT_NOP: 822 (void)printf("\nNOP"); 823 break; 824 default: 825 (void)printf("\nunknown option %x", *cp); 826 break; 827 } 828 if (!(options & F_FLOOD)) { 829 (void)putchar('\n'); 830 (void)fflush(stdout); 831 } 832} 833 834/* 835 * in_cksum -- 836 * Checksum routine for Internet Protocol family headers (C Version) 837 */ 838u_short 839in_cksum(addr, len) 840 u_short *addr; 841 int len; 842{ 843 register int nleft = len; 844 register u_short *w = addr; 845 register int sum = 0; 846 u_short answer = 0; 847 848 /* 849 * Our algorithm is simple, using a 32 bit accumulator (sum), we add 850 * sequential 16 bit words to it, and at the end, fold back all the 851 * carry bits from the top 16 bits into the lower 16 bits. 852 */ 853 while (nleft > 1) { 854 sum += *w++; 855 nleft -= 2; 856 } 857 858 /* mop up an odd byte, if necessary */ 859 if (nleft == 1) { 860 *(u_char *)(&answer) = *(u_char *)w ; 861 sum += answer; 862 } 863 864 /* add back carry outs from top 16 bits to low 16 bits */ 865 sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */ 866 sum += (sum >> 16); /* add carry */ 867 answer = ~sum; /* truncate to 16 bits */ 868 return(answer); 869} 870 871/* 872 * tvsub -- 873 * Subtract 2 timeval structs: out = out - in. Out is assumed to 874 * be >= in. 875 */ 876static void 877tvsub(out, in) 878 register struct timeval *out, *in; 879{ 880 if ((out->tv_usec -= in->tv_usec) < 0) { 881 --out->tv_sec; 882 out->tv_usec += 1000000; 883 } 884 out->tv_sec -= in->tv_sec; 885} 886 887/* 888 * status -- 889 * Print out statistics when SIGINFO is received. 890 */ 891 892static void 893status(sig) 894 int sig; 895{ 896 siginfo_p = 1; 897} 898 899static void 900check_status() 901{ 902 if (siginfo_p) { 903 siginfo_p = 0; 904 (void)fprintf(stderr, 905 "\r%ld/%ld packets received (%.0f%%) %.3f min / %.3f avg / %.3f max\n", 906 nreceived, ntransmitted, 907 ntransmitted ? nreceived * 100.0 / ntransmitted : 0.0, 908 nreceived ? tmin : 0.0, 909 nreceived + nrepeats ? tsum / (nreceived + nrepeats) : tsum, 910 tmax); 911 } 912} 913 914/* 915 * finish -- 916 * Print out statistics, and give up. 917 */ 918static void 919finish() 920{ 921 struct termios ts; 922 923 (void)signal(SIGINT, SIG_IGN); 924 (void)signal(SIGALRM, SIG_IGN); 925 (void)putchar('\n'); 926 (void)fflush(stdout); 927 (void)printf("--- %s ping statistics ---\n", hostname); 928 (void)printf("%ld packets transmitted, ", ntransmitted); 929 (void)printf("%ld packets received, ", nreceived); 930 if (nrepeats) 931 (void)printf("+%ld duplicates, ", nrepeats); 932 if (ntransmitted) 933 if (nreceived > ntransmitted) 934 (void)printf("-- somebody's printing up packets!"); 935 else 936 (void)printf("%d%% packet loss", 937 (int) (((ntransmitted - nreceived) * 100) / 938 ntransmitted)); 939 (void)putchar('\n'); 940 if (nreceived && timing) { 941 double n = nreceived + nrepeats; 942 double avg = tsum / n; 943 double vari = tsumsq / n - avg * avg; 944 printf("round-trip min/avg/max/stddev = " 945 "%.3f/%.3f/%.3f/%.3f ms\n", 946 tmin, avg, tmax, sqrt(vari)); 947 } 948 if (reset_kerninfo && tcgetattr(STDOUT_FILENO, &ts) != -1) { 949 ts.c_lflag &= ~NOKERNINFO; 950 tcsetattr(STDOUT_FILENO, TCSANOW, &ts); 951 } 952 953 if (nreceived) 954 exit(0); 955 else 956 exit(2); 957} 958 959#ifdef notdef 960static char *ttab[] = { 961 "Echo Reply", /* ip + seq + udata */ 962 "Dest Unreachable", /* net, host, proto, port, frag, sr + IP */ 963 "Source Quench", /* IP */ 964 "Redirect", /* redirect type, gateway, + IP */ 965 "Echo", 966 "Time Exceeded", /* transit, frag reassem + IP */ 967 "Parameter Problem", /* pointer + IP */ 968 "Timestamp", /* id + seq + three timestamps */ 969 "Timestamp Reply", /* " */ 970 "Info Request", /* id + sq */ 971 "Info Reply" /* " */ 972}; 973#endif 974 975/* 976 * pr_icmph -- 977 * Print a descriptive string about an ICMP header. 978 */ 979static void 980pr_icmph(icp) 981 struct icmp *icp; 982{ 983 switch(icp->icmp_type) { 984 case ICMP_ECHOREPLY: 985 (void)printf("Echo Reply\n"); 986 /* XXX ID + Seq + Data */ 987 break; 988 case ICMP_UNREACH: 989 switch(icp->icmp_code) { 990 case ICMP_UNREACH_NET: 991 (void)printf("Destination Net Unreachable\n"); 992 break; 993 case ICMP_UNREACH_HOST: 994 (void)printf("Destination Host Unreachable\n"); 995 break; 996 case ICMP_UNREACH_PROTOCOL: 997 (void)printf("Destination Protocol Unreachable\n"); 998 break; 999 case ICMP_UNREACH_PORT: 1000 (void)printf("Destination Port Unreachable\n"); 1001 break; 1002 case ICMP_UNREACH_NEEDFRAG: 1003 (void)printf("frag needed and DF set (MTU %d)\n", 1004 ntohs(icp->icmp_nextmtu)); 1005 break; 1006 case ICMP_UNREACH_SRCFAIL: 1007 (void)printf("Source Route Failed\n"); 1008 break; 1009 case ICMP_UNREACH_FILTER_PROHIB: 1010 (void)printf("Communication prohibited by filter\n"); 1011 break; 1012 default: 1013 (void)printf("Dest Unreachable, Bad Code: %d\n", 1014 icp->icmp_code); 1015 break; 1016 } 1017 /* Print returned IP header information */ 1018#ifndef icmp_data 1019 pr_retip(&icp->icmp_ip); 1020#else 1021 pr_retip((struct ip *)icp->icmp_data); 1022#endif 1023 break; 1024 case ICMP_SOURCEQUENCH: 1025 (void)printf("Source Quench\n"); 1026#ifndef icmp_data 1027 pr_retip(&icp->icmp_ip); 1028#else 1029 pr_retip((struct ip *)icp->icmp_data); 1030#endif 1031 break; 1032 case ICMP_REDIRECT: 1033 switch(icp->icmp_code) { 1034 case ICMP_REDIRECT_NET: 1035 (void)printf("Redirect Network"); 1036 break; 1037 case ICMP_REDIRECT_HOST: 1038 (void)printf("Redirect Host"); 1039 break; 1040 case ICMP_REDIRECT_TOSNET: 1041 (void)printf("Redirect Type of Service and Network"); 1042 break; 1043 case ICMP_REDIRECT_TOSHOST: 1044 (void)printf("Redirect Type of Service and Host"); 1045 break; 1046 default: 1047 (void)printf("Redirect, Bad Code: %d", icp->icmp_code); 1048 break; 1049 } 1050 (void)printf("(New addr: %s)\n", inet_ntoa(icp->icmp_gwaddr)); 1051#ifndef icmp_data 1052 pr_retip(&icp->icmp_ip); 1053#else 1054 pr_retip((struct ip *)icp->icmp_data); 1055#endif 1056 break; 1057 case ICMP_ECHO: 1058 (void)printf("Echo Request\n"); 1059 /* XXX ID + Seq + Data */ 1060 break; 1061 case ICMP_TIMXCEED: 1062 switch(icp->icmp_code) { 1063 case ICMP_TIMXCEED_INTRANS: 1064 (void)printf("Time to live exceeded\n"); 1065 break; 1066 case ICMP_TIMXCEED_REASS: 1067 (void)printf("Frag reassembly time exceeded\n"); 1068 break; 1069 default: 1070 (void)printf("Time exceeded, Bad Code: %d\n", 1071 icp->icmp_code); 1072 break; 1073 } 1074#ifndef icmp_data 1075 pr_retip(&icp->icmp_ip); 1076#else 1077 pr_retip((struct ip *)icp->icmp_data); 1078#endif 1079 break; 1080 case ICMP_PARAMPROB: 1081 (void)printf("Parameter problem: pointer = 0x%02x\n", 1082 icp->icmp_hun.ih_pptr); 1083#ifndef icmp_data 1084 pr_retip(&icp->icmp_ip); 1085#else 1086 pr_retip((struct ip *)icp->icmp_data); 1087#endif 1088 break; 1089 case ICMP_TSTAMP: 1090 (void)printf("Timestamp\n"); 1091 /* XXX ID + Seq + 3 timestamps */ 1092 break; 1093 case ICMP_TSTAMPREPLY: 1094 (void)printf("Timestamp Reply\n"); 1095 /* XXX ID + Seq + 3 timestamps */ 1096 break; 1097 case ICMP_IREQ: 1098 (void)printf("Information Request\n"); 1099 /* XXX ID + Seq */ 1100 break; 1101 case ICMP_IREQREPLY: 1102 (void)printf("Information Reply\n"); 1103 /* XXX ID + Seq */ 1104 break; 1105 case ICMP_MASKREQ: 1106 (void)printf("Address Mask Request\n"); 1107 break; 1108 case ICMP_MASKREPLY: 1109 (void)printf("Address Mask Reply\n"); 1110 break; 1111 case ICMP_ROUTERADVERT: 1112 (void)printf("Router Advertisement\n"); 1113 break; 1114 case ICMP_ROUTERSOLICIT: 1115 (void)printf("Router Solicitation\n"); 1116 break; 1117 default: 1118 (void)printf("Bad ICMP type: %d\n", icp->icmp_type); 1119 } 1120} 1121 1122/* 1123 * pr_iph -- 1124 * Print an IP header with options. 1125 */ 1126static void 1127pr_iph(ip) 1128 struct ip *ip; 1129{ 1130 int hlen; 1131 u_char *cp; 1132 1133 hlen = ip->ip_hl << 2; 1134 cp = (u_char *)ip + 20; /* point to options */ 1135 1136 (void)printf("Vr HL TOS Len ID Flg off TTL Pro cks Src Dst\n"); 1137 (void)printf(" %1x %1x %02x %04x %04x", 1138 ip->ip_v, ip->ip_hl, ip->ip_tos, ntohs(ip->ip_len), 1139 ntohs(ip->ip_id)); 1140 (void)printf(" %1lx %04lx", (ntohl(ip->ip_off) & 0xe000) >> 13, 1141 ntohl(ip->ip_off) & 0x1fff); 1142 (void)printf(" %02x %02x %04x", ip->ip_ttl, ip->ip_p, 1143 ntohs(ip->ip_sum)); 1144 (void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_src.s_addr)); 1145 (void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_dst.s_addr)); 1146 /* dump any option bytes */ 1147 while (hlen-- > 20) { 1148 (void)printf("%02x", *cp++); 1149 } 1150 (void)putchar('\n'); 1151} 1152 1153/* 1154 * pr_addr -- 1155 * Return an ascii host address as a dotted quad and optionally with 1156 * a hostname. 1157 */ 1158static char * 1159pr_addr(ina) 1160 struct in_addr ina; 1161{ 1162 struct hostent *hp; 1163 static char buf[16 + 3 + MAXHOSTNAMELEN]; 1164 1165 if ((options & F_NUMERIC) || 1166 !(hp = gethostbyaddr((char *)&ina, 4, AF_INET))) 1167 return inet_ntoa(ina); 1168 else 1169 (void)snprintf(buf, sizeof(buf), "%s (%s)", hp->h_name, 1170 inet_ntoa(ina)); 1171 return(buf); 1172} 1173 1174/* 1175 * pr_retip -- 1176 * Dump some info on a returned (via ICMP) IP packet. 1177 */ 1178static void 1179pr_retip(ip) 1180 struct ip *ip; 1181{ 1182 int hlen; 1183 u_char *cp; 1184 1185 pr_iph(ip); 1186 hlen = ip->ip_hl << 2; 1187 cp = (u_char *)ip + hlen; 1188 1189 if (ip->ip_p == 6) 1190 (void)printf("TCP: from port %u, to port %u (decimal)\n", 1191 (*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3))); 1192 else if (ip->ip_p == 17) 1193 (void)printf("UDP: from port %u, to port %u (decimal)\n", 1194 (*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3))); 1195} 1196 1197static void 1198fill(bp, patp) 1199 char *bp, *patp; 1200{ 1201 register int ii, jj, kk; 1202 int pat[16]; 1203 char *cp; 1204 1205 for (cp = patp; *cp; cp++) { 1206 if (!isxdigit(*cp)) 1207 errx(EX_USAGE, 1208 "patterns must be specified as hex digits"); 1209 1210 } 1211 ii = sscanf(patp, 1212 "%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x", 1213 &pat[0], &pat[1], &pat[2], &pat[3], &pat[4], &pat[5], &pat[6], 1214 &pat[7], &pat[8], &pat[9], &pat[10], &pat[11], &pat[12], 1215 &pat[13], &pat[14], &pat[15]); 1216 1217 if (ii > 0) 1218 for (kk = 0; 1219 kk <= MAXPACKET - (8 + sizeof(struct timeval) + ii); 1220 kk += ii) 1221 for (jj = 0; jj < ii; ++jj) 1222 bp[jj + kk] = pat[jj]; 1223 if (!(options & F_QUIET)) { 1224 (void)printf("PATTERN: 0x"); 1225 for (jj = 0; jj < ii; ++jj) 1226 (void)printf("%02x", bp[jj] & 0xFF); 1227 (void)printf("\n"); 1228 } 1229} 1230 1231static void 1232usage(argv0) 1233 const char *argv0; 1234{ 1235 if (strrchr(argv0,'/')) 1236 argv0 = strrchr(argv0,'/') + 1; 1237 fprintf(stderr, 1238 "usage: %s [-QRadfnqrv] [-c count] [-i wait] [-l preload] " 1239 "[-p pattern]\n [-s packetsize] " 1240 "[host | [-L] [-I iface] [-T ttl] mcast-group]\n", 1241 argv0); 1242 exit(EX_USAGE); 1243} 1244