1 /* $NetBSD: ping.c,v 1.30 1997/06/01 19:34:49 christos Exp $ */ 2 3 /* 4 * Copyright (c) 1989, 1993 5 * The Regents of the University of California. All rights reserved. 6 * 7 * This code is derived from software contributed to Berkeley by 8 * Mike Muuss. 9 * 10 * Redistribution and use in source and binary forms, with or without 11 * modification, are permitted provided that the following conditions 12 * are met: 13 * 1. Redistributions of source code must retain the above copyright 14 * notice, this list of conditions and the following disclaimer. 15 * 2. Redistributions in binary form must reproduce the above copyright 16 * notice, this list of conditions and the following disclaimer in the 17 * documentation and/or other materials provided with the distribution. 18 * 3. All advertising materials mentioning features or use of this software 19 * must display the following acknowledgement: 20 * This product includes software developed by the University of 21 * California, Berkeley and its contributors. 22 * 4. Neither the name of the University nor the names of its contributors 23 * may be used to endorse or promote products derived from this software 24 * without specific prior written permission. 25 * 26 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 27 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 28 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 29 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 30 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 31 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 32 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 33 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 34 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 35 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 36 * SUCH DAMAGE. 37 */ 38 /* 39 * P I N G . C 40 * 41 * Using the InterNet Control Message Protocol (ICMP) "ECHO" facility, 42 * measure round-trip-delays and packet loss across network paths. 43 * 44 * Author - 45 * Mike Muuss 46 * U. S. Army Ballistic Research Laboratory 47 * December, 1983 48 * Modified at Uc Berkeley 49 * Record Route and verbose headers - Phil Dykstra, BRL, March 1988. 50 * Multicast options (ttl, if, loop) - Steve Deering, Stanford, August 1988. 51 * ttl, duplicate detection - Cliff Frost, UCB, April 1989 52 * Pad pattern - Cliff Frost (from Tom Ferrin, UCSF), April 1989 53 * 54 * Status - 55 * Public Domain. Distribution Unlimited. 56 * 57 * Bugs - 58 * More statistics could always be gathered. 59 * This program has to run SUID to ROOT to access the ICMP socket. 60 */ 61 62 #ifndef lint 63 static char rcsid[] = "$NetBSD: ping.c,v 1.30 1997/06/01 19:34:49 christos Exp $"; 64 #endif 65 66 #include <stdio.h> 67 #include <errno.h> 68 #include <sys/time.h> 69 #include <sys/types.h> 70 #include <sys/signal.h> 71 #include <sys/param.h> 72 #include <sys/socket.h> 73 #include <sys/file.h> 74 #include <termios.h> 75 #include <stdlib.h> 76 #include <unistd.h> 77 #include <limits.h> 78 #include <string.h> 79 #include <err.h> 80 #ifdef sgi 81 #include <bstring.h> 82 #include <getopt.h> 83 #include <sys/prctl.h> 84 #include <sys/schedctl.h> 85 #endif 86 87 #include <netinet/in_systm.h> 88 #include <netinet/in.h> 89 #include <netinet/ip.h> 90 #include <netinet/ip_icmp.h> 91 #include <netinet/ip_var.h> 92 #include <arpa/inet.h> 93 #include <ctype.h> 94 #include <netdb.h> 95 96 #define FLOOD_INTVL 0.01 /* default flood output interval */ 97 #define MAXPACKET (65536-60-8) /* max packet size */ 98 99 #define F_VERBOSE 0x0001 100 #define F_QUIET 0x0002 /* minimize all output */ 101 #define F_SEMI_QUIET 0x0004 /* ignore our ICMP errors */ 102 #define F_FLOOD 0x0008 /* flood-ping */ 103 #define F_RECORD_ROUTE 0x0010 /* record route */ 104 #define F_SOURCE_ROUTE 0x0020 /* loose source route */ 105 #define F_PING_FILLED 0x0040 /* is buffer filled with user data? */ 106 #define F_PING_RANDOM 0x0080 /* use random data */ 107 #define F_NUMERIC 0x0100 /* do not do gethostbyaddr() calls */ 108 #define F_TIMING 0x0200 /* room for a timestamp */ 109 #define F_DF 0x0400 /* set IP DF bit */ 110 #define F_SOURCE_ADDR 0x0800 /* set source IP address/interface */ 111 #define F_ONCE 0x1000 /* exit(0) after receiving 1 reply */ 112 #define F_MCAST 0x2000 /* multicast target */ 113 #define F_MCAST_NOLOOP 0x4000 /* no multicast loopback */ 114 115 /* MAX_DUP_CHK is the number of bits in received table, the 116 * maximum number of received sequence numbers we can track to check 117 * for duplicates. 118 */ 119 #define MAX_DUP_CHK (8 * 2048) 120 u_char rcvd_tbl[MAX_DUP_CHK/8]; 121 int nrepeats = 0; 122 #define A(seq) rcvd_tbl[(seq/8)%sizeof(rcvd_tbl)] /* byte in array */ 123 #define B(seq) (1 << (seq & 0x07)) /* bit in byte */ 124 #define SET(seq) (A(seq) |= B(seq)) 125 #define CLR(seq) (A(seq) &= (~B(seq))) 126 #define TST(seq) (A(seq) & B(seq)) 127 128 129 130 u_char *packet; 131 int packlen; 132 int pingflags = 0, options; 133 char *fill_pat; 134 135 int s; /* Socket file descriptor */ 136 137 #define PHDR_LEN sizeof(struct timeval) /* size of timestamp header */ 138 struct sockaddr_in whereto, send_addr; /* Who to ping */ 139 struct sockaddr_in src_addr; /* from where */ 140 struct sockaddr_in loc_addr; /* 127.1 */ 141 int datalen = 64-PHDR_LEN; /* How much data */ 142 143 #ifdef sgi 144 static char *__progname; 145 #else 146 extern char *__progname; 147 #endif 148 149 150 char hostname[MAXHOSTNAMELEN]; 151 152 static struct { 153 struct ip o_ip; 154 char o_opt[MAX_IPOPTLEN]; 155 union { 156 u_char u_buf[MAXPACKET]; 157 struct icmp u_icmp; 158 } o_u; 159 } out_pack; 160 #define opack_icmp out_pack.o_u.u_icmp 161 struct ip *opack_ip; 162 163 char optspace[MAX_IPOPTLEN]; /* record route space */ 164 int optlen; 165 166 167 int npackets; /* total packets to send */ 168 int preload; /* number of packets to "preload" */ 169 int ntransmitted; /* output sequence # = #sent */ 170 int ident; 171 172 int nreceived; /* # of packets we got back */ 173 174 double interval; /* interval between packets */ 175 struct timeval interval_tv; 176 double tmin = 999999999; 177 double tmax = 0; 178 double tsum = 0; /* sum of all times */ 179 double maxwait = 0; 180 181 #ifdef SIGINFO 182 int reset_kerninfo; 183 #endif 184 185 int bufspace = 60*1024; 186 187 struct timeval now, clear_cache, last_tx, next_tx, first_tx; 188 struct timeval last_rx, first_rx; 189 int lastrcvd = 1; /* last ping sent has been received */ 190 191 static struct timeval jiggle_time; 192 static int jiggle_cnt, total_jiggled, jiggle_direction = -1; 193 194 static void doit(void); 195 static void prefinish(int); 196 static void prtsig(int); 197 static void finish(int); 198 static void summary(int); 199 static void pinger(void); 200 static void fill(void); 201 static void rnd_fill(void); 202 static double diffsec(struct timeval *, struct timeval *); 203 static void timevaladd(struct timeval *, struct timeval *); 204 static void sec_to_timeval(const double, struct timeval *); 205 static double timeval_to_sec(const struct timeval *); 206 static void pr_pack(u_char *, int, struct sockaddr_in *); 207 static u_short in_cksum(u_short *, u_int); 208 static void pr_saddr(char *, u_char *); 209 static char *pr_addr(struct in_addr *); 210 static void pr_iph(struct icmp *, int); 211 static void pr_retip(struct icmp *, int); 212 static int pr_icmph(struct icmp *, struct sockaddr_in *, int); 213 static void jiggle(int), jiggle_flush(int); 214 static void gethost(const char *, const char *, 215 struct sockaddr_in *, char *, int); 216 static void usage(void); 217 218 219 int 220 main(int argc, char *argv[]) 221 { 222 int c, i, on = 1, hostind = 0; 223 long l; 224 u_char ttl = 0; 225 u_long tos = 0; 226 char *p; 227 #ifdef SIGINFO 228 struct termios ts; 229 #endif 230 231 232 #if defined(SIGINFO) && defined(NOKERNINFO) 233 if (tcgetattr (0, &ts) != -1) { 234 reset_kerninfo = !(ts.c_lflag & NOKERNINFO); 235 ts.c_lflag |= NOKERNINFO; 236 tcsetattr (0, TCSANOW, &ts); 237 } 238 #endif 239 while ((c = getopt(argc, argv, 240 "c:dDfg:h:i:I:l:Lnop:PqQrRs:t:T:vw:")) != -1) { 241 switch (c) { 242 case 'c': 243 npackets = strtol(optarg, &p, 0); 244 if (*p != '\0' || npackets <= 0) 245 errx(1, "Bad/invalid number of packets"); 246 break; 247 case 'D': 248 pingflags |= F_DF; 249 break; 250 case 'd': 251 options |= SO_DEBUG; 252 break; 253 case 'f': 254 pingflags |= F_FLOOD; 255 break; 256 case 'h': 257 hostind = optind-1; 258 break; 259 case 'i': /* wait between sending packets */ 260 interval = strtod(optarg, &p); 261 if (*p != '\0' || interval <= 0) 262 errx(1, "Bad/invalid interval %s", optarg); 263 break; 264 case 'l': 265 preload = strtol(optarg, &p, 0); 266 if (*p != '\0' || preload < 0) 267 errx(1, "Bad/invalid preload value %s", 268 optarg); 269 break; 270 case 'n': 271 pingflags |= F_NUMERIC; 272 break; 273 case 'o': 274 pingflags |= F_ONCE; 275 break; 276 case 'p': /* fill buffer with user pattern */ 277 if (pingflags & F_PING_RANDOM) 278 errx(1, "Only one of -P and -p allowed"); 279 pingflags |= F_PING_FILLED; 280 fill_pat = optarg; 281 break; 282 case 'P': 283 if (pingflags & F_PING_FILLED) 284 errx(1, "Only one of -P and -p allowed"); 285 pingflags |= F_PING_RANDOM; 286 break; 287 case 'q': 288 pingflags |= F_QUIET; 289 break; 290 case 'Q': 291 pingflags |= F_SEMI_QUIET; 292 break; 293 case 'r': 294 options |= SO_DONTROUTE; 295 break; 296 case 's': /* size of packet to send */ 297 datalen = strtol(optarg, &p, 0); 298 if (*p != '\0' || datalen <= 0) 299 errx(1, "Bad/invalid packet size %s", optarg); 300 if (datalen > MAXPACKET) 301 errx(1, "packet size is too large"); 302 break; 303 case 'v': 304 pingflags |= F_VERBOSE; 305 break; 306 case 'R': 307 pingflags |= F_RECORD_ROUTE; 308 break; 309 case 'L': 310 pingflags |= F_MCAST_NOLOOP; 311 break; 312 case 't': 313 tos = strtoul(optarg, &p, 0); 314 if (*p != '\0' || tos > 0xFF) 315 errx(1, "bad tos value: %s", optarg); 316 break; 317 case 'T': 318 l = strtol(optarg, &p, 0); 319 if (*p != '\0' || l > 255 || l <= 0) 320 errx(1, "ttl out of range"); 321 ttl = (u_char)l; /* cannot check >255 otherwise */ 322 break; 323 case 'I': 324 pingflags |= F_SOURCE_ADDR; 325 gethost("-I", optarg, &src_addr, 0, 0); 326 break; 327 case 'g': 328 pingflags |= F_SOURCE_ROUTE; 329 gethost("-g", optarg, &send_addr, 0, 0); 330 break; 331 case 'w': 332 maxwait = strtod(optarg, &p); 333 if (*p != '\0' || maxwait <= 0) 334 errx(1, "Bad/invalid maxwait time %s", optarg); 335 break; 336 default: 337 usage(); 338 break; 339 } 340 } 341 342 if (interval == 0) 343 interval = (pingflags & F_FLOOD) ? FLOOD_INTVL : 1.0; 344 #ifndef sgi 345 if (interval < 1.0 && getuid()) 346 errx(1, "Must be superuser to use < 1 sec ping interval"); 347 #endif 348 sec_to_timeval(interval, &interval_tv); 349 350 if (npackets != 0) { 351 npackets += preload; 352 } else { 353 npackets = INT_MAX; 354 } 355 356 if (hostind == 0) { 357 if (optind != argc-1) 358 usage(); 359 else 360 hostind = optind; 361 } 362 else if (hostind >= argc - 1) 363 usage(); 364 365 gethost("", argv[hostind], &whereto, hostname, sizeof(hostname)); 366 if (IN_MULTICAST(ntohl(whereto.sin_addr.s_addr))) 367 pingflags |= F_MCAST; 368 if (!(pingflags & F_SOURCE_ROUTE)) 369 (void) memcpy(&send_addr, &whereto, sizeof(send_addr)); 370 371 loc_addr.sin_family = AF_INET; 372 loc_addr.sin_addr.s_addr = htonl((127<<24)+1); 373 374 if (datalen >= PHDR_LEN) /* can we time them? */ 375 pingflags |= F_TIMING; 376 packlen = datalen + 60 + 76; /* MAXIP + MAXICMP */ 377 if ((packet = (u_char *)malloc(packlen)) == NULL) 378 err(1, "Out of memory"); 379 380 if (pingflags & F_PING_FILLED) { 381 fill(); 382 } else if (pingflags & F_PING_RANDOM) { 383 rnd_fill(); 384 } else { 385 for (i = PHDR_LEN; i < datalen; i++) 386 opack_icmp.icmp_data[i] = i; 387 } 388 389 ident = getpid() & 0xFFFF; 390 391 if ((s = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP)) < 0) 392 err(1, "Cannot create socket"); 393 if (options & SO_DEBUG) { 394 if (setsockopt(s, SOL_SOCKET, SO_DEBUG, (char *) &on, 395 sizeof(on)) == -1) 396 warn("Can't turn on socket debugging"); 397 } 398 if (options & SO_DONTROUTE) { 399 if (setsockopt(s, SOL_SOCKET, SO_DONTROUTE, (char *) &on, 400 sizeof(on)) == -1) 401 warn("SO_DONTROUTE"); 402 } 403 404 if (pingflags & F_SOURCE_ROUTE) { 405 optspace[IPOPT_OPTVAL] = IPOPT_LSRR; 406 optspace[IPOPT_OLEN] = optlen = 7; 407 optspace[IPOPT_OFFSET] = IPOPT_MINOFF; 408 (void) memcpy(&whereto.sin_addr, &optspace[IPOPT_MINOFF-1], 409 sizeof(whereto.sin_addr)); 410 optspace[optlen++] = IPOPT_NOP; 411 } 412 if (pingflags & F_RECORD_ROUTE) { 413 optspace[optlen+IPOPT_OPTVAL] = IPOPT_RR; 414 optspace[optlen+IPOPT_OLEN] = (MAX_IPOPTLEN -1-optlen); 415 optspace[optlen+IPOPT_OFFSET] = IPOPT_MINOFF; 416 optlen = MAX_IPOPTLEN; 417 } 418 /* this leaves opack_ip 0(mod 4) aligned */ 419 opack_ip = (struct ip *)((char *)&out_pack.o_ip 420 + sizeof(out_pack.o_opt) 421 - optlen); 422 (void) memcpy(opack_ip + 1, optspace, optlen); 423 424 if (setsockopt(s,IPPROTO_IP,IP_HDRINCL, (char *) &on, sizeof(on)) < 0) 425 err(1, "Can't set special IP header"); 426 427 opack_ip->ip_v = IPVERSION; 428 opack_ip->ip_hl = (sizeof(struct ip)+optlen) >> 2; 429 opack_ip->ip_tos = tos; 430 opack_ip->ip_off = (pingflags & F_DF) ? IP_DF : 0; 431 opack_ip->ip_ttl = ttl ? ttl : MAXTTL; 432 opack_ip->ip_p = IPPROTO_ICMP; 433 opack_ip->ip_src = src_addr.sin_addr; 434 opack_ip->ip_dst = send_addr.sin_addr; 435 436 if (pingflags & F_MCAST) { 437 if (pingflags & F_MCAST_NOLOOP) { 438 u_char loop = 0; 439 if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_LOOP, 440 (char *) &loop, 1) < 0) 441 err(1, "Can't disable multicast loopback"); 442 } 443 444 if (ttl != 0 445 && setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL, 446 (char *) &ttl, 1) < 0) 447 err(1, "Can't set multicast time-to-live"); 448 449 if ((pingflags & F_SOURCE_ADDR) 450 && setsockopt(s, IPPROTO_IP, IP_MULTICAST_IF, 451 (char *) &src_addr.sin_addr, 452 sizeof(src_addr.sin_addr)) < 0) 453 err(1, "Can't set multicast source interface"); 454 455 } else if (pingflags & F_SOURCE_ADDR) { 456 if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_IF, 457 (char *) &src_addr.sin_addr, 458 sizeof(src_addr.sin_addr)) < 0) 459 err(1, "Can't set source interface/address"); 460 } 461 462 (void)printf("PING %s (%s): %d data bytes\n", hostname, 463 inet_ntoa(whereto.sin_addr), datalen); 464 465 /* When pinging the broadcast address, you can get a lot 466 * of answers. Doing something so evil is useful if you 467 * are trying to stress the ethernet, or just want to 468 * fill the arp cache to get some stuff for /etc/ethers. 469 */ 470 while (0 > setsockopt(s, SOL_SOCKET, SO_RCVBUF, 471 (char*)&bufspace, sizeof(bufspace))) { 472 if ((bufspace -= 4096) == 0) 473 err(1, "Cannot set the receive buffer size"); 474 } 475 476 /* make it possible to send giant probes, but do not worry now 477 * if it fails, since we probably won't send giant probes. 478 */ 479 (void)setsockopt(s, SOL_SOCKET, SO_SNDBUF, 480 (char*)&bufspace, sizeof(bufspace)); 481 482 (void)signal(SIGINT, prefinish); 483 #ifdef SIGINFO 484 (void)signal(SIGINFO, prtsig); 485 #else 486 (void)signal(SIGQUIT, prtsig); 487 #endif 488 (void)signal(SIGCONT, prtsig); 489 490 #ifdef sgi 491 /* run with a non-degrading priority to improve the delay values. */ 492 (void) cap_schedctl(NDPRI, 0, NDPHIMAX); 493 #endif 494 495 /* fire off them quickies */ 496 for (i = 0; i < preload; i++) { 497 (void)gettimeofday(&now, 0); 498 pinger(); 499 } 500 501 doit(); 502 return 0; 503 } 504 505 506 static void 507 doit(void) 508 { 509 int cc; 510 struct sockaddr_in from; 511 int fromlen; 512 double sec, last, d_last; 513 struct timeval timeout; 514 fd_set fdmask; 515 516 517 (void)gettimeofday(&clear_cache,0); 518 if (maxwait != 0) { 519 last = timeval_to_sec(&clear_cache) + maxwait; 520 d_last = 0; 521 } else { 522 last = 0; 523 d_last = 365*24*60*60; 524 } 525 526 FD_ZERO(&fdmask); 527 do { 528 (void)gettimeofday(&now,0); 529 530 if (last != 0) 531 d_last = last - timeval_to_sec(&now); 532 533 if (ntransmitted < npackets && d_last > 0) { 534 /* send if within 100 usec or late for next packet */ 535 sec = diffsec(&next_tx,&now); 536 if (sec <= 0.0001 537 || (lastrcvd && (pingflags & F_FLOOD))) { 538 pinger(); 539 sec = diffsec(&next_tx,&now); 540 } 541 if (sec < 0.0) 542 sec = 0.0; 543 if (d_last < sec) 544 sec = d_last; 545 546 } else { 547 /* For the last response, wait twice as long as the 548 * worst case seen, or 10 times as long as the 549 * maximum interpacket interval, whichever is longer. 550 */ 551 sec = MAX(2*tmax,10*interval) - diffsec(&now,&last_tx); 552 if (d_last < sec) 553 sec = d_last; 554 if (sec <= 0) 555 break; 556 } 557 558 559 sec_to_timeval(sec, &timeout); 560 561 FD_SET(s, &fdmask); 562 cc = select(s+1, &fdmask, 0, 0, &timeout); 563 if (cc <= 0) { 564 if (cc < 0) { 565 if (errno == EINTR) 566 continue; 567 jiggle_flush(1); 568 err(1, "select"); 569 } 570 continue; 571 } 572 573 fromlen = sizeof(from); 574 cc = recvfrom(s, (char *) packet, packlen, 575 0, (struct sockaddr *)&from, 576 &fromlen); 577 if (cc < 0) { 578 if (errno != EINTR) { 579 jiggle_flush(1); 580 warn("recvfrom"); 581 (void)fflush(stderr); 582 } 583 continue; 584 } 585 (void)gettimeofday(&now, 0); 586 pr_pack(packet, cc, &from); 587 588 } while (nreceived < npackets 589 && (nreceived == 0 || !(pingflags & F_ONCE))); 590 591 finish(0); 592 } 593 594 595 static void 596 jiggle_flush(int nl) /* new line if there are dots */ 597 { 598 int serrno = errno; 599 600 if (jiggle_cnt > 0) { 601 total_jiggled += jiggle_cnt; 602 jiggle_direction = 1; 603 do { 604 (void)putchar('.'); 605 } while (--jiggle_cnt > 0); 606 607 } else if (jiggle_cnt < 0) { 608 total_jiggled -= jiggle_cnt; 609 jiggle_direction = -1; 610 do { 611 (void)putchar('\b'); 612 } while (++jiggle_cnt < 0); 613 } 614 615 if (nl) { 616 if (total_jiggled != 0) 617 (void)putchar('\n'); 618 total_jiggled = 0; 619 jiggle_direction = -1; 620 } 621 622 (void)fflush(stdout); 623 (void)fflush(stderr); 624 jiggle_time = now; 625 errno = serrno; 626 } 627 628 629 /* jiggle the cursor for flood-ping 630 */ 631 static void 632 jiggle(int delta) 633 { 634 double dt; 635 636 if (pingflags & F_QUIET) 637 return; 638 639 /* do not back up into messages */ 640 if (total_jiggled+jiggle_cnt+delta < 0) 641 return; 642 643 jiggle_cnt += delta; 644 645 /* flush the FLOOD dots when things are quiet 646 * or occassionally to make the cursor jiggle. 647 */ 648 dt = diffsec(&last_tx, &jiggle_time); 649 if (dt > 0.2 || (dt >= 0.15 && delta*jiggle_direction < 0)) 650 jiggle_flush(0); 651 } 652 653 654 /* 655 * Compose and transmit an ICMP ECHO REQUEST packet. The IP packet 656 * will be added on by the kernel. The ID field is our UNIX process ID, 657 * and the sequence number is an ascending integer. The first PHDR_LEN bytes 658 * of the data portion are used to hold a UNIX "timeval" struct in VAX 659 * byte-order, to compute the round-trip time. 660 */ 661 static void 662 pinger(void) 663 { 664 int i, cc, sw; 665 666 opack_icmp.icmp_code = 0; 667 opack_icmp.icmp_seq = htons((u_short)(ntransmitted)); 668 669 /* clear the cached route in the kernel after an ICMP 670 * response such as a Redirect is seen to stop causing 671 * more such packets. Also clear the cached route 672 * periodically in case of routing changes that make 673 * black holes come and go. 674 */ 675 if (clear_cache.tv_sec != now.tv_sec) { 676 opack_icmp.icmp_type = ICMP_ECHOREPLY; 677 opack_icmp.icmp_id = ~ident; 678 opack_icmp.icmp_cksum = 0; 679 opack_icmp.icmp_cksum = in_cksum((u_short*)&opack_icmp, 680 PHDR_LEN); 681 sw = 0; 682 if (setsockopt(s,IPPROTO_IP,IP_HDRINCL, 683 (char *)&sw,sizeof(sw)) < 0) 684 err(1, "Can't turn off special IP header"); 685 if (sendto(s, (char *) &opack_icmp, PHDR_LEN, MSG_DONTROUTE, 686 (struct sockaddr *)&loc_addr, 687 sizeof(struct sockaddr_in)) < 0) 688 err(1, "failed to clear cached route"); 689 sw = 1; 690 if (setsockopt(s,IPPROTO_IP,IP_HDRINCL, 691 (char *)&sw, sizeof(sw)) < 0) 692 err(1, "Can't set special IP header"); 693 694 (void)gettimeofday(&clear_cache,0); 695 } 696 697 opack_icmp.icmp_type = ICMP_ECHO; 698 opack_icmp.icmp_id = ident; 699 if (pingflags & F_TIMING) 700 (void) memcpy(&opack_icmp.icmp_data[0], &now, sizeof(now)); 701 cc = datalen+PHDR_LEN; 702 opack_icmp.icmp_cksum = 0; 703 opack_icmp.icmp_cksum = in_cksum((u_short*)&opack_icmp, cc); 704 705 cc += opack_ip->ip_hl<<2; 706 opack_ip->ip_len = cc; 707 i = sendto(s, (char *) opack_ip, cc, 0, 708 (struct sockaddr *)&send_addr, sizeof(struct sockaddr_in)); 709 if (i != cc) { 710 jiggle_flush(1); 711 if (i < 0) 712 warn("sendto"); 713 else 714 warnx("wrote %s %d chars, ret=%d", hostname, cc, i); 715 (void)fflush(stderr); 716 } 717 lastrcvd = 0; 718 719 CLR(ntransmitted); 720 ntransmitted++; 721 722 last_tx = now; 723 if (next_tx.tv_sec == 0) { 724 first_tx = now; 725 next_tx = now; 726 } 727 728 /* Transmit regularly, at always the same microsecond in the 729 * second when going at one packet per second. 730 * If we are at most 100 ms behind, send extras to get caught up. 731 * Otherwise, skip packets we were too slow to send. 732 */ 733 if (diffsec(&next_tx, &now) <= interval) { 734 do { 735 timevaladd(&next_tx, &interval_tv); 736 } while (diffsec(&next_tx, &now) < -0.1); 737 } 738 739 if (pingflags & F_FLOOD) 740 jiggle(1); 741 742 /* While the packet is going out, ready buffer for the next 743 * packet. Use a fast but not very good random number generator. 744 */ 745 if (pingflags & F_PING_RANDOM) 746 rnd_fill(); 747 } 748 749 750 static void 751 pr_pack_sub(int cc, 752 char *addr, 753 int seqno, 754 int dupflag, 755 int ttl, 756 double triptime) 757 { 758 jiggle_flush(1); 759 760 if (pingflags & F_FLOOD) 761 return; 762 763 (void)printf("%d bytes from %s: icmp_seq=%u", cc, addr, seqno); 764 if (dupflag) 765 (void)printf(" DUP!"); 766 (void)printf(" ttl=%d", ttl); 767 if (pingflags & F_TIMING) 768 (void)printf(" time=%.3f ms", triptime*1000.0); 769 } 770 771 772 /* 773 * Print out the packet, if it came from us. This logic is necessary 774 * because ALL readers of the ICMP socket get a copy of ALL ICMP packets 775 * which arrive ('tis only fair). This permits multiple copies of this 776 * program to be run without having intermingled output (or statistics!). 777 */ 778 static void 779 pr_pack(u_char *buf, 780 int cc, 781 struct sockaddr_in *from) 782 { 783 struct ip *ip; 784 register struct icmp *icp; 785 register int i, j; 786 register u_char *cp; 787 static int old_rrlen; 788 static char old_rr[MAX_IPOPTLEN]; 789 int hlen, dupflag = 0, dumped; 790 double triptime = 0.0; 791 #define PR_PACK_SUB() {if (!dumped) { \ 792 dumped = 1; \ 793 pr_pack_sub(cc, inet_ntoa(from->sin_addr), \ 794 ntohs((u_short)icp->icmp_seq), \ 795 dupflag, ip->ip_ttl, triptime);}} 796 797 /* Check the IP header */ 798 ip = (struct ip *) buf; 799 hlen = ip->ip_hl << 2; 800 if (cc < hlen + ICMP_MINLEN) { 801 if (pingflags & F_VERBOSE) { 802 jiggle_flush(1); 803 (void)printf("packet too short (%d bytes) from %s\n", 804 cc, inet_ntoa(from->sin_addr)); 805 } 806 return; 807 } 808 809 /* Now the ICMP part */ 810 dumped = 0; 811 cc -= hlen; 812 icp = (struct icmp *)(buf + hlen); 813 if (icp->icmp_type == ICMP_ECHOREPLY 814 && icp->icmp_id == ident) { 815 816 if (icp->icmp_seq == htons((u_short)(ntransmitted-1))) 817 lastrcvd = 1; 818 last_rx = now; 819 if (first_rx.tv_sec == 0) 820 first_rx = last_rx; 821 nreceived++; 822 if (pingflags & F_TIMING) { 823 struct timeval tv; 824 (void) memcpy(&tv, icp->icmp_data, sizeof(tv)); 825 triptime = diffsec(&last_rx, &tv); 826 tsum += triptime; 827 if (triptime < tmin) 828 tmin = triptime; 829 if (triptime > tmax) 830 tmax = triptime; 831 } 832 833 if (TST(ntohs((u_short)icp->icmp_seq))) { 834 nrepeats++, nreceived--; 835 dupflag=1; 836 } else { 837 SET(ntohs((u_short)icp->icmp_seq)); 838 } 839 840 if (pingflags & F_QUIET) 841 return; 842 843 if (!(pingflags & F_FLOOD)) 844 PR_PACK_SUB(); 845 846 /* check the data */ 847 if (datalen > PHDR_LEN 848 && !(pingflags & F_PING_RANDOM) 849 && memcmp(&icp->icmp_data[PHDR_LEN], 850 &opack_icmp.icmp_data[PHDR_LEN], 851 datalen-PHDR_LEN)) { 852 for (i=PHDR_LEN; i<datalen; i++) { 853 if (icp->icmp_data[PHDR_LEN+i] 854 != opack_icmp.icmp_data[PHDR_LEN+i]) 855 break; 856 } 857 PR_PACK_SUB(); 858 (void)printf("\nwrong data byte #%d should have been" 859 " %#x but was %#x", 860 i, (u_char)opack_icmp.icmp_data[i], 861 (u_char)icp->icmp_data[i]); 862 for (i=PHDR_LEN; i<datalen; i++) { 863 if ((i%16) == PHDR_LEN) 864 (void)printf("\n\t"); 865 (void)printf("%2x ",(u_char)icp->icmp_data[i]); 866 } 867 } 868 869 } else { 870 if (!pr_icmph(icp, from, cc)) 871 return; 872 dumped = 2; 873 } 874 875 /* Display any IP options */ 876 cp = buf + sizeof(struct ip); 877 while (hlen > (int)sizeof(struct ip)) { 878 switch (*cp) { 879 case IPOPT_EOL: 880 hlen = 0; 881 break; 882 case IPOPT_LSRR: 883 hlen -= 2; 884 j = *++cp; 885 ++cp; 886 j -= IPOPT_MINOFF; 887 if (j <= 0) 888 continue; 889 if (dumped <= 1) { 890 j = ((j+3)/4)*4; 891 hlen -= j; 892 cp += j; 893 break; 894 } 895 PR_PACK_SUB(); 896 (void)printf("\nLSRR: "); 897 for (;;) { 898 pr_saddr("\t%s", cp); 899 cp += 4; 900 hlen -= 4; 901 j -= 4; 902 if (j <= 0) 903 break; 904 (void)putchar('\n'); 905 } 906 break; 907 case IPOPT_RR: 908 j = *++cp; /* get length */ 909 i = *++cp; /* and pointer */ 910 hlen -= 2; 911 if (i > j) 912 i = j; 913 i -= IPOPT_MINOFF; 914 if (i <= 0) 915 continue; 916 if (dumped <= 1) { 917 if (i == old_rrlen 918 && !memcmp(cp, old_rr, i)) { 919 if (dumped) 920 (void)printf("\t(same route)"); 921 j = ((i+3)/4)*4; 922 hlen -= j; 923 cp += j; 924 break; 925 } 926 old_rrlen = i; 927 (void) memcpy(old_rr, cp, i); 928 } 929 if (!dumped) { 930 jiggle_flush(1); 931 (void)printf("RR: "); 932 dumped = 1; 933 } else { 934 (void)printf("\nRR: "); 935 } 936 for (;;) { 937 pr_saddr("\t%s", cp); 938 cp += 4; 939 hlen -= 4; 940 i -= 4; 941 if (i <= 0) 942 break; 943 (void)putchar('\n'); 944 } 945 break; 946 case IPOPT_NOP: 947 if (dumped <= 1) 948 break; 949 PR_PACK_SUB(); 950 (void)printf("\nNOP"); 951 break; 952 #ifdef sgi 953 case IPOPT_SECURITY: /* RFC 1108 RIPSO BSO */ 954 case IPOPT_ESO: /* RFC 1108 RIPSO ESO */ 955 case IPOPT_CIPSO: /* Commercial IPSO */ 956 if ((sysconf(_SC_IP_SECOPTS)) > 0) { 957 i = (unsigned)cp[1]; 958 hlen -= i - 1; 959 PR_PACK_SUB(); 960 (void)printf("\nSEC:"); 961 while (i--) { 962 (void)printf(" %02x", *cp++); 963 } 964 cp--; 965 break; 966 } 967 #endif 968 default: 969 PR_PACK_SUB(); 970 (void)printf("\nunknown option %x", *cp); 971 break; 972 } 973 hlen--; 974 cp++; 975 } 976 977 if (dumped) { 978 (void)putchar('\n'); 979 (void)fflush(stdout); 980 } else { 981 jiggle(-1); 982 } 983 } 984 985 986 /* Compute the IP checksum 987 * This assumes the packet is less than 32K long. 988 */ 989 static u_short 990 in_cksum(u_short *p, 991 u_int len) 992 { 993 u_int sum = 0; 994 int nwords = len >> 1; 995 996 while (nwords-- != 0) 997 sum += *p++; 998 999 if (len & 1) { 1000 union { 1001 u_short w; 1002 u_char c[2]; 1003 } u; 1004 u.c[0] = *(u_char *)p; 1005 u.c[1] = 0; 1006 sum += u.w; 1007 } 1008 1009 /* end-around-carry */ 1010 sum = (sum >> 16) + (sum & 0xffff); 1011 sum += (sum >> 16); 1012 return (~sum); 1013 } 1014 1015 1016 /* 1017 * compute the difference of two timevals in seconds 1018 */ 1019 static double 1020 diffsec(struct timeval *now, 1021 struct timeval *then) 1022 { 1023 return ((now->tv_sec - then->tv_sec)*1.0 1024 + (now->tv_usec - then->tv_usec)/1000000.0); 1025 } 1026 1027 1028 static void 1029 timevaladd(struct timeval *t1, 1030 struct timeval *t2) 1031 { 1032 1033 t1->tv_sec += t2->tv_sec; 1034 if ((t1->tv_usec += t2->tv_usec) > 1000000) { 1035 t1->tv_sec++; 1036 t1->tv_usec -= 1000000; 1037 } 1038 } 1039 1040 1041 static void 1042 sec_to_timeval(const double sec, struct timeval *tp) 1043 { 1044 tp->tv_sec = sec; 1045 tp->tv_usec = (sec - tp->tv_sec) * 1000000.0; 1046 } 1047 1048 static double 1049 timeval_to_sec(const struct timeval *tp) 1050 { 1051 return tp->tv_sec + tp->tv_usec / 1000000.0; 1052 } 1053 1054 1055 /* 1056 * Print statistics. 1057 * Heavily buffered STDIO is used here, so that all the statistics 1058 * will be written with 1 sys-write call. This is nice when more 1059 * than one copy of the program is running on a terminal; it prevents 1060 * the statistics output from becomming intermingled. 1061 */ 1062 static void 1063 summary(int header) 1064 { 1065 jiggle_flush(1); 1066 1067 if (header) 1068 (void)printf("\n----%s PING Statistics----\n", hostname); 1069 (void)printf("%d packets transmitted, ", ntransmitted); 1070 (void)printf("%d packets received, ", nreceived); 1071 if (nrepeats) 1072 (void)printf("+%d duplicates, ", nrepeats); 1073 if (ntransmitted) { 1074 if (nreceived > ntransmitted) 1075 (void)printf("-- somebody's printing up packets!"); 1076 else 1077 (void)printf("%d%% packet loss", 1078 (int) (((ntransmitted-nreceived)*100) / 1079 ntransmitted)); 1080 } 1081 (void)printf("\n"); 1082 if (nreceived && (pingflags & F_TIMING)) { 1083 (void)printf("round-trip min/avg/max = %.3f/%.3f/%.3f ms\n", 1084 tmin*1000.0, 1085 (tsum/(nreceived+nrepeats))*1000.0, 1086 tmax*1000.0); 1087 if (pingflags & F_FLOOD) { 1088 double r = diffsec(&last_rx, &first_rx); 1089 double t = diffsec(&last_tx, &first_tx); 1090 if (r == 0) 1091 r = 0.0001; 1092 if (t == 0) 1093 t = 0.0001; 1094 (void)printf(" %.1f packets/sec sent, " 1095 " %.1f packets/sec received\n", 1096 ntransmitted/t, nreceived/r); 1097 } 1098 } 1099 } 1100 1101 1102 /* 1103 * Print statistics when SIGINFO is received. 1104 */ 1105 /* ARGSUSED */ 1106 static void 1107 prtsig(int s) 1108 { 1109 summary(0); 1110 #ifdef SIGINFO 1111 (void)signal(SIGINFO, prtsig); 1112 #else 1113 (void)signal(SIGQUIT, prtsig); 1114 #endif 1115 } 1116 1117 1118 /* 1119 * On the first SIGINT, allow any outstanding packets to dribble in 1120 */ 1121 static void 1122 prefinish(int s) 1123 { 1124 if (lastrcvd /* quit now if caught up */ 1125 || nreceived == 0) /* or if remote is dead */ 1126 finish(0); 1127 1128 signal(s, finish); /* do this only the 1st time */ 1129 1130 if (npackets > ntransmitted) /* let the normal limit work */ 1131 npackets = ntransmitted; 1132 } 1133 1134 1135 /* 1136 * Print statistics and give up. 1137 */ 1138 /* ARGSUSED */ 1139 static void 1140 finish(int s) 1141 { 1142 #if defined(SIGINFO) && defined(NOKERNINFO) 1143 struct termios ts; 1144 1145 if (reset_kerninfo && tcgetattr (0, &ts) != -1) { 1146 ts.c_lflag &= ~NOKERNINFO; 1147 tcsetattr (0, TCSANOW, &ts); 1148 } 1149 (void)signal(SIGINFO, SIG_IGN); 1150 #else 1151 (void)signal(SIGQUIT, SIG_DFL); 1152 #endif 1153 1154 summary(1); 1155 exit(nreceived > 0 ? 0 : 2); 1156 } 1157 1158 1159 static int /* 0=do not print it */ 1160 ck_pr_icmph(struct icmp *icp, 1161 struct sockaddr_in *from, 1162 int cc, 1163 int override) /* 1=override VERBOSE if interesting */ 1164 { 1165 int hlen; 1166 struct ip ip; 1167 struct icmp icp2; 1168 int res; 1169 1170 if (pingflags & F_VERBOSE) { 1171 res = 1; 1172 jiggle_flush(1); 1173 } else { 1174 res = 0; 1175 } 1176 1177 (void) memcpy(&ip, icp->icmp_data, sizeof(ip)); 1178 hlen = ip.ip_hl << 2; 1179 if (ip.ip_p == IPPROTO_ICMP 1180 && hlen + 6 <= cc) { 1181 (void) memcpy(&icp2, &icp->icmp_data[hlen], sizeof(icp2)); 1182 if (icp2.icmp_id == ident) { 1183 /* remember to clear route cached in kernel 1184 * if this ICMP message was for one of our packet. 1185 */ 1186 clear_cache.tv_sec = 0; 1187 1188 if (!res && override 1189 && (pingflags & (F_QUIET|F_SEMI_QUIET)) == 0) { 1190 jiggle_flush(1); 1191 (void)printf("%d bytes from %s: ", 1192 cc, pr_addr(&from->sin_addr)); 1193 res = 1; 1194 } 1195 } 1196 } 1197 1198 return res; 1199 } 1200 1201 1202 /* 1203 * Print a descriptive string about an ICMP header other than an echo reply. 1204 */ 1205 static int /* 0=printed nothing */ 1206 pr_icmph(struct icmp *icp, 1207 struct sockaddr_in *from, 1208 int cc) 1209 { 1210 switch (icp->icmp_type ) { 1211 case ICMP_UNREACH: 1212 if (!ck_pr_icmph(icp, from, cc, 1)) 1213 return 0; 1214 switch (icp->icmp_code) { 1215 case ICMP_UNREACH_NET: 1216 (void)printf("Destination Net Unreachable"); 1217 break; 1218 case ICMP_UNREACH_HOST: 1219 (void)printf("Destination Host Unreachable"); 1220 break; 1221 case ICMP_UNREACH_PROTOCOL: 1222 (void)printf("Destination Protocol Unreachable"); 1223 break; 1224 case ICMP_UNREACH_PORT: 1225 (void)printf("Destination Port Unreachable"); 1226 break; 1227 case ICMP_UNREACH_NEEDFRAG: 1228 (void)printf("frag needed and DF set. Next MTU=%d", 1229 icp->icmp_nextmtu); 1230 break; 1231 case ICMP_UNREACH_SRCFAIL: 1232 (void)printf("Source Route Failed"); 1233 break; 1234 case ICMP_UNREACH_NET_UNKNOWN: 1235 (void)printf("Unreachable unknown net"); 1236 break; 1237 case ICMP_UNREACH_HOST_UNKNOWN: 1238 (void)printf("Unreachable unknown host"); 1239 break; 1240 case ICMP_UNREACH_ISOLATED: 1241 (void)printf("Unreachable host isolated"); 1242 break; 1243 case ICMP_UNREACH_NET_PROHIB: 1244 (void)printf("Net prohibited access"); 1245 break; 1246 case ICMP_UNREACH_HOST_PROHIB: 1247 (void)printf("Host prohibited access"); 1248 break; 1249 case ICMP_UNREACH_TOSNET: 1250 (void)printf("Bad TOS for net"); 1251 break; 1252 case ICMP_UNREACH_TOSHOST: 1253 (void)printf("Bad TOS for host"); 1254 break; 1255 case 13: 1256 (void)printf("Communication prohibited"); 1257 break; 1258 case 14: 1259 (void)printf("Host precedence violation"); 1260 break; 1261 case 15: 1262 (void)printf("Precedence cutoff"); 1263 break; 1264 default: 1265 (void)printf("Bad Destination Unreachable Code: %d", 1266 icp->icmp_code); 1267 break; 1268 } 1269 /* Print returned IP header information */ 1270 pr_retip(icp, cc); 1271 break; 1272 1273 case ICMP_SOURCEQUENCH: 1274 if (!ck_pr_icmph(icp, from, cc, 1)) 1275 return 0; 1276 (void)printf("Source Quench"); 1277 pr_retip(icp, cc); 1278 break; 1279 1280 case ICMP_REDIRECT: 1281 if (!ck_pr_icmph(icp, from, cc, 1)) 1282 return 0; 1283 switch (icp->icmp_code) { 1284 case ICMP_REDIRECT_NET: 1285 (void)printf("Redirect: Network"); 1286 break; 1287 case ICMP_REDIRECT_HOST: 1288 (void)printf("Redirect: Host"); 1289 break; 1290 case ICMP_REDIRECT_TOSNET: 1291 (void)printf("Redirect: Type of Service and Network"); 1292 break; 1293 case ICMP_REDIRECT_TOSHOST: 1294 (void)printf("Redirect: Type of Service and Host"); 1295 break; 1296 default: 1297 (void)printf("Redirect: Bad Code: %d", icp->icmp_code); 1298 break; 1299 } 1300 (void)printf(" New addr: %s", 1301 pr_addr(&icp->icmp_hun.ih_gwaddr)); 1302 pr_retip(icp, cc); 1303 break; 1304 1305 case ICMP_ECHO: 1306 if (!ck_pr_icmph(icp, from, cc, 0)) 1307 return 0; 1308 (void)printf("Echo Request: ID=%d seq=%d", 1309 icp->icmp_id, icp->icmp_seq); 1310 break; 1311 1312 case ICMP_ECHOREPLY: 1313 /* displaying other's pings is too noisey */ 1314 #if 0 1315 if (!ck_pr_icmph(icp, from, cc, 0)) 1316 return 0; 1317 (void)printf("Echo Reply: ID=%d seq=%d", 1318 icp->icmp_id, icp->icmp_seq); 1319 break; 1320 #else 1321 return 0; 1322 #endif 1323 1324 case ICMP_ROUTERADVERT: 1325 if (!ck_pr_icmph(icp, from, cc, 0)) 1326 return 0; 1327 (void)printf("Router Discovery Advert"); 1328 break; 1329 1330 case ICMP_ROUTERSOLICIT: 1331 if (!ck_pr_icmph(icp, from, cc, 0)) 1332 return 0; 1333 (void)printf("Router Discovery Solicit"); 1334 break; 1335 1336 case ICMP_TIMXCEED: 1337 if (!ck_pr_icmph(icp, from, cc, 1)) 1338 return 0; 1339 switch (icp->icmp_code ) { 1340 case ICMP_TIMXCEED_INTRANS: 1341 (void)printf("Time To Live exceeded"); 1342 break; 1343 case ICMP_TIMXCEED_REASS: 1344 (void)printf("Frag reassembly time exceeded"); 1345 break; 1346 default: 1347 (void)printf("Time exceeded, Bad Code: %d", 1348 icp->icmp_code); 1349 break; 1350 } 1351 pr_retip(icp, cc); 1352 break; 1353 1354 case ICMP_PARAMPROB: 1355 if (!ck_pr_icmph(icp, from, cc, 1)) 1356 return 0; 1357 (void)printf("Parameter problem: pointer = 0x%02x", 1358 icp->icmp_hun.ih_pptr); 1359 pr_retip(icp, cc); 1360 break; 1361 1362 case ICMP_TSTAMP: 1363 if (!ck_pr_icmph(icp, from, cc, 0)) 1364 return 0; 1365 (void)printf("Timestamp"); 1366 break; 1367 1368 case ICMP_TSTAMPREPLY: 1369 if (!ck_pr_icmph(icp, from, cc, 0)) 1370 return 0; 1371 (void)printf("Timestamp Reply"); 1372 break; 1373 1374 case ICMP_IREQ: 1375 if (!ck_pr_icmph(icp, from, cc, 0)) 1376 return 0; 1377 (void)printf("Information Request"); 1378 break; 1379 1380 case ICMP_IREQREPLY: 1381 if (!ck_pr_icmph(icp, from, cc, 0)) 1382 return 0; 1383 (void)printf("Information Reply"); 1384 break; 1385 1386 case ICMP_MASKREQ: 1387 if (!ck_pr_icmph(icp, from, cc, 0)) 1388 return 0; 1389 (void)printf("Address Mask Request"); 1390 break; 1391 1392 case ICMP_MASKREPLY: 1393 if (!ck_pr_icmph(icp, from, cc, 0)) 1394 return 0; 1395 (void)printf("Address Mask Reply"); 1396 break; 1397 1398 default: 1399 if (!ck_pr_icmph(icp, from, cc, 0)) 1400 return 0; 1401 (void)printf("Bad ICMP type: %d", icp->icmp_type); 1402 if (pingflags & F_VERBOSE) 1403 pr_iph(icp, cc); 1404 } 1405 1406 return 1; 1407 } 1408 1409 1410 /* 1411 * Print an IP header with options. 1412 */ 1413 static void 1414 pr_iph(struct icmp *icp, 1415 int cc) 1416 { 1417 int hlen; 1418 u_char *cp; 1419 struct ip ip; 1420 1421 (void) memcpy(&ip, icp->icmp_data, sizeof(ip)); 1422 1423 hlen = ip.ip_hl << 2; 1424 cp = (u_char *) &icp->icmp_data[20]; /* point to options */ 1425 1426 (void)printf("\n Vr HL TOS Len ID Flg off TTL Pro cks Src Dst\n"); 1427 (void)printf(" %1x %1x %02x %04x %04x", 1428 ip.ip_v, ip.ip_hl, ip.ip_tos, ip.ip_len, ip.ip_id); 1429 (void)printf(" %1x %04x", 1430 ((ip.ip_off)&0xe000)>>13, (ip.ip_off)&0x1fff); 1431 (void)printf(" %02x %02x %04x", 1432 ip.ip_ttl, ip.ip_p, ip.ip_sum); 1433 (void)printf(" %15s ", 1434 inet_ntoa(*(struct in_addr *)&ip.ip_src.s_addr)); 1435 (void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip.ip_dst.s_addr)); 1436 /* dump any option bytes */ 1437 while (hlen-- > 20 && cp < (u_char*)icp+cc) { 1438 (void)printf("%02x", *cp++); 1439 } 1440 } 1441 1442 /* 1443 * Print an ASCII host address starting from a string of bytes. 1444 */ 1445 static void 1446 pr_saddr(char *pat, 1447 u_char *cp) 1448 { 1449 register n_long l; 1450 struct in_addr addr; 1451 1452 l = (u_char)*++cp; 1453 l = (l<<8) + (u_char)*++cp; 1454 l = (l<<8) + (u_char)*++cp; 1455 l = (l<<8) + (u_char)*++cp; 1456 addr.s_addr = htonl(l); 1457 (void)printf(pat, (l == 0) ? "0.0.0.0" : pr_addr(&addr)); 1458 } 1459 1460 1461 /* 1462 * Return an ASCII host address 1463 * as a dotted quad and optionally with a hostname 1464 */ 1465 static char * 1466 pr_addr(struct in_addr *addr) /* in network order */ 1467 { 1468 struct hostent *hp; 1469 static char buf[MAXHOSTNAMELEN+4+16+1]; 1470 1471 if ((pingflags & F_NUMERIC) 1472 || !(hp = gethostbyaddr((char *)addr, sizeof(*addr), AF_INET))) { 1473 (void)sprintf(buf, "%s", inet_ntoa(*addr)); 1474 } else { 1475 (void)sprintf(buf, "%s (%s)", hp->h_name, inet_ntoa(*addr)); 1476 } 1477 1478 return buf; 1479 } 1480 1481 /* 1482 * Dump some info on a returned (via ICMP) IP packet. 1483 */ 1484 static void 1485 pr_retip(struct icmp *icp, 1486 int cc) 1487 { 1488 int hlen; 1489 u_char *cp; 1490 struct ip ip; 1491 1492 (void) memcpy(&ip, icp->icmp_data, sizeof(ip)); 1493 1494 if (pingflags & F_VERBOSE) 1495 pr_iph(icp, cc); 1496 1497 hlen = ip.ip_hl << 2; 1498 cp = (u_char *) &icp->icmp_data[hlen]; 1499 1500 if (ip.ip_p == IPPROTO_TCP) { 1501 if (pingflags & F_VERBOSE) 1502 (void)printf("\n TCP: from port %u, to port %u", 1503 (*cp*256+*(cp+1)), (*(cp+2)*256+*(cp+3))); 1504 } else if (ip.ip_p == IPPROTO_UDP) { 1505 if (pingflags & F_VERBOSE) 1506 (void)printf("\n UDP: from port %u, to port %u", 1507 (*cp*256+*(cp+1)), (*(cp+2)*256+*(cp+3))); 1508 } else if (ip.ip_p == IPPROTO_ICMP) { 1509 struct icmp icp2; 1510 (void) memcpy(&icp2, cp, sizeof(icp2)); 1511 if (icp2.icmp_type == ICMP_ECHO) { 1512 if (pingflags & F_VERBOSE) 1513 (void)printf("\n ID=%u icmp_seq=%u", 1514 icp2.icmp_id, 1515 icp2.icmp_seq); 1516 else 1517 (void)printf(" for icmp_seq=%u", 1518 icp2.icmp_seq); 1519 } 1520 } 1521 } 1522 1523 static void 1524 fill(void) 1525 { 1526 register int i, j, k; 1527 char *cp; 1528 int pat[16]; 1529 1530 for (cp = fill_pat; *cp != '\0'; cp++) { 1531 if (!isxdigit(*cp)) 1532 break; 1533 } 1534 if (cp == fill_pat || *cp != '\0' || (cp-fill_pat) > 16*2) { 1535 (void)fflush(stdout); 1536 errx(1, "\"-p %s\": patterns must be specified with" 1537 " 1-32 hex digits\n", 1538 fill_pat); 1539 } 1540 1541 i = sscanf(fill_pat, 1542 "%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x", 1543 &pat[0], &pat[1], &pat[2], &pat[3], 1544 &pat[4], &pat[5], &pat[6], &pat[7], 1545 &pat[8], &pat[9], &pat[10], &pat[11], 1546 &pat[12], &pat[13], &pat[14], &pat[15]); 1547 1548 for (k=PHDR_LEN, j = 0; k <= datalen; k++) { 1549 opack_icmp.icmp_data[k] = pat[j]; 1550 if (++j >= i) 1551 j = 0; 1552 } 1553 1554 if (!(pingflags & F_QUIET)) { 1555 (void)printf("PATTERN: 0x"); 1556 for (j=0; j<i; j++) 1557 (void)printf("%02x", 1558 (u_char)opack_icmp.icmp_data[PHDR_LEN+j]); 1559 (void)printf("\n"); 1560 } 1561 1562 } 1563 1564 1565 static void 1566 rnd_fill(void) 1567 { 1568 static u_int rnd; 1569 int i; 1570 1571 for (i = PHDR_LEN; i < datalen; i++) { 1572 rnd = (314157*rnd + 66329) & 0xffff; 1573 opack_icmp.icmp_data[i] = rnd>>8; 1574 } 1575 } 1576 1577 static void 1578 gethost(const char *arg, 1579 const char *name, 1580 struct sockaddr_in *sa, 1581 char *realname, 1582 int realname_len) 1583 { 1584 struct hostent *hp; 1585 1586 bzero(sa, sizeof(*sa)); 1587 sa->sin_family = AF_INET; 1588 1589 /* If it is an IP address, try to convert it to a name to 1590 * have something nice to display. 1591 */ 1592 if (inet_aton(name, &sa->sin_addr) != 0) { 1593 if (realname) { 1594 if (pingflags & F_NUMERIC) 1595 hp = 0; 1596 else 1597 hp = gethostbyaddr((char *)&sa->sin_addr, 1598 sizeof(sa->sin_addr), 1599 AF_INET); 1600 (void)strncpy(realname, hp ? hp->h_name : name, 1601 realname_len); 1602 realname[realname_len-1] = '\0'; 1603 } 1604 return; 1605 } 1606 1607 hp = gethostbyname(name); 1608 if (!hp) 1609 errx(1, "Cannot resolve \"%s\" (%s)",name,hstrerror(h_errno)); 1610 1611 if (hp->h_addrtype != AF_INET) 1612 errx(1, "%s only supported with IP", arg); 1613 1614 bcopy(hp->h_addr, &sa->sin_addr, sizeof(sa->sin_addr)); 1615 1616 if (realname) { 1617 (void)strncpy(realname, hp->h_name, realname_len); 1618 realname[realname_len-1] = '\0'; 1619 } 1620 } 1621 1622 1623 static void 1624 usage(void) 1625 { 1626 (void)fprintf(stderr, "Usage: \n" 1627 "%s [-dDfnqrvRLP] [-c count] [-s size] [-l preload]" 1628 " [-p pattern]\n" 1629 " [-i interval] [-i maxwait] [-t tos] [-T ttl]" 1630 " [-I addr] [-g gateway] host\n", 1631 __progname); 1632 exit(1); 1633 } 1634