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