1 /* 2 * Copyright (c) 1989, 1993 3 * The Regents of the University of California. All rights reserved. 4 * 5 * This code is derived from software contributed to Berkeley by 6 * Mike Muuss. 7 * 8 * Redistribution and use in source and binary forms, with or without 9 * modification, are permitted provided that the following conditions 10 * are met: 11 * 1. Redistributions of source code must retain the above copyright 12 * notice, this list of conditions and the following disclaimer. 13 * 2. Redistributions in binary form must reproduce the above copyright 14 * notice, this list of conditions and the following disclaimer in the 15 * documentation and/or other materials provided with the distribution. 16 * 3. All advertising materials mentioning features or use of this software 17 * must display the following acknowledgement: 18 * This product includes software developed by the University of 19 * California, Berkeley and its contributors. 20 * 4. Neither the name of the University nor the names of its contributors 21 * may be used to endorse or promote products derived from this software 22 * without specific prior written permission. 23 * 24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 34 * SUCH DAMAGE. 35 */ 36 37 #ifndef lint 38 static 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 #if 0 45 static char sccsid[] = "@(#)ping.c 8.1 (Berkeley) 6/5/93"; 46 #endif 47 static const char rcsid[] = 48 "$FreeBSD$"; 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/time.h> 86 #include <sys/uio.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 #ifdef IPSEC 96 #include <netinet6/ipsec.h> 97 #endif /*IPSEC*/ 98 99 #define PHDR_LEN sizeof(struct timeval) 100 #define DEFDATALEN (64 - PHDR_LEN) /* default data length */ 101 #define FLOOD_BACKOFF 20000 /* usecs to back off if F_FLOOD mode */ 102 /* runs out of buffer space */ 103 #define MAXIPLEN 60 104 #define MAXICMPLEN 76 105 #define MAXPACKET (65536 - 60 - 8)/* max packet size */ 106 #define MAXWAIT 10 /* max seconds to wait for response */ 107 #define MAXALARM (60 * 60) /* max seconds for alarm timeout */ 108 #define NROUTES 9 /* number of record route slots */ 109 110 #define A(bit) rcvd_tbl[(bit)>>3] /* identify byte in array */ 111 #define B(bit) (1 << ((bit) & 0x07)) /* identify bit in byte */ 112 #define SET(bit) (A(bit) |= B(bit)) 113 #define CLR(bit) (A(bit) &= (~B(bit))) 114 #define TST(bit) (A(bit) & B(bit)) 115 116 /* various options */ 117 int options; 118 #define F_FLOOD 0x0001 119 #define F_INTERVAL 0x0002 120 #define F_NUMERIC 0x0004 121 #define F_PINGFILLED 0x0008 122 #define F_QUIET 0x0010 123 #define F_RROUTE 0x0020 124 #define F_SO_DEBUG 0x0040 125 #define F_SO_DONTROUTE 0x0080 126 #define F_VERBOSE 0x0100 127 #define F_QUIET2 0x0200 128 #define F_NOLOOP 0x0400 129 #define F_MTTL 0x0800 130 #define F_MIF 0x1000 131 #define F_AUDIBLE 0x2000 132 #ifdef IPSEC 133 #ifdef IPSEC_POLICY_IPSEC 134 #define F_POLICY 0x4000 135 #endif /*IPSEC_POLICY_IPSEC*/ 136 #endif /*IPSEC*/ 137 #define F_TTL 0x8000 138 #define F_MISSED 0x10000 139 140 /* 141 * MAX_DUP_CHK is the number of bits in received table, i.e. the maximum 142 * number of received sequence numbers we can keep track of. Change 128 143 * to 8192 for complete accuracy... 144 */ 145 #define MAX_DUP_CHK (8 * 128) 146 int mx_dup_ck = MAX_DUP_CHK; 147 char rcvd_tbl[MAX_DUP_CHK / 8]; 148 149 struct sockaddr_in whereto; /* who to ping */ 150 int datalen = DEFDATALEN; 151 int s; /* socket file descriptor */ 152 u_char outpack[MAXPACKET]; 153 char BSPACE = '\b'; /* characters written for flood */ 154 char BBELL = '\a'; /* characters written for MISSED and AUDIBLE */ 155 char DOT = '.'; 156 char *hostname; 157 char *shostname; 158 int ident; /* process id to identify our packets */ 159 int uid; /* cached uid for micro-optimization */ 160 161 /* counters */ 162 long npackets; /* max packets to transmit */ 163 long nreceived; /* # of packets we got back */ 164 long nrepeats; /* number of duplicates */ 165 long ntransmitted; /* sequence # for outbound packets = #sent */ 166 long nmissedmax; /* max value of ntransmitted - nreceived - 1 */ 167 int interval = 1000; /* interval between packets, ms */ 168 169 /* timing */ 170 int timing; /* flag to do timing */ 171 double tmin = 999999999.0; /* minimum round trip time */ 172 double tmax = 0.0; /* maximum round trip time */ 173 double tsum = 0.0; /* sum of all times, for doing average */ 174 double tsumsq = 0.0; /* sum of all times squared, for std. dev. */ 175 176 volatile sig_atomic_t finish_up; /* nonzero if we've been told to finish up */ 177 int reset_kerninfo; 178 volatile sig_atomic_t siginfo_p; 179 180 static void fill(char *, char *); 181 static u_short in_cksum(u_short *, int); 182 static void check_status(void); 183 static void finish(void) __dead2; 184 static void pinger(void); 185 static char *pr_addr(struct in_addr); 186 static void pr_icmph(struct icmp *); 187 static void pr_iph(struct ip *); 188 static void pr_pack(char *, int, struct sockaddr_in *, struct timeval *); 189 static void pr_retip(struct ip *); 190 static void status(int); 191 static void stopit(int); 192 static void tvsub(struct timeval *, struct timeval *); 193 static void usage(void) __dead2; 194 195 int 196 main(argc, argv) 197 int argc; 198 char *const *argv; 199 { 200 struct in_addr ifaddr; 201 struct iovec iov; 202 struct msghdr msg; 203 struct sigaction si_sa; 204 struct sockaddr_in from, sin; 205 struct termios ts; 206 struct timeval last, intvl; 207 struct hostent *hp; 208 struct sockaddr_in *to; 209 u_char *datap, *packet; 210 char *ep, *source, *target; 211 #ifdef IPSEC_POLICY_IPSEC 212 char *policy_in, *policy_out; 213 #endif 214 u_long alarmtimeout, ultmp; 215 int ch, hold, i, packlen, preload, sockerrno, almost_done = 0, ttl; 216 char ctrl[CMSG_SPACE(sizeof(struct timeval))]; 217 char hnamebuf[MAXHOSTNAMELEN], snamebuf[MAXHOSTNAMELEN]; 218 #ifdef IP_OPTIONS 219 char rspace[3 + 4 * NROUTES + 1]; /* record route space */ 220 #endif 221 unsigned char mttl, loop; 222 223 source = NULL; 224 #ifdef IPSEC_POLICY_IPSEC 225 policy_in = policy_out = NULL; 226 #endif 227 228 /* 229 * Do the stuff that we need root priv's for *first*, and 230 * then drop our setuid bit. Save error reporting for 231 * after arg parsing. 232 */ 233 s = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP); 234 sockerrno = errno; 235 236 setuid(getuid()); 237 uid = getuid(); 238 239 alarmtimeout = preload = 0; 240 241 datap = &outpack[8 + PHDR_LEN]; 242 while ((ch = getopt(argc, argv, 243 "AI:LQRS:T:c:adfi:l:m:np:qrs:t:v" 244 #ifdef IPSEC 245 #ifdef IPSEC_POLICY_IPSEC 246 "P:" 247 #endif /*IPSEC_POLICY_IPSEC*/ 248 #endif /*IPSEC*/ 249 )) != -1) 250 { 251 switch(ch) { 252 case 'A': 253 options |= F_MISSED; 254 break; 255 case 'a': 256 options |= F_AUDIBLE; 257 break; 258 case 'c': 259 ultmp = strtoul(optarg, &ep, 0); 260 if (*ep || ep == optarg || ultmp > LONG_MAX || !ultmp) 261 errx(EX_USAGE, 262 "invalid count of packets to transmit: `%s'", 263 optarg); 264 npackets = ultmp; 265 break; 266 case 'd': 267 options |= F_SO_DEBUG; 268 break; 269 case 'f': 270 if (uid) { 271 errno = EPERM; 272 err(EX_NOPERM, "-f flag"); 273 } 274 options |= F_FLOOD; 275 setbuf(stdout, (char *)NULL); 276 break; 277 case 'i': /* wait between sending packets */ 278 { 279 double t = strtod(optarg, &ep) * 1000.0; 280 281 if (*ep || ep == optarg || t > (double)INT_MAX) { 282 errx( 283 EX_USAGE, 284 "invalid timing interval: `%s'", 285 optarg 286 ); 287 } 288 options |= F_INTERVAL; 289 interval = (int)t; 290 if (uid && interval < 1000) { 291 errno = EPERM; 292 err(EX_NOPERM, "-i interval too short"); 293 } 294 } 295 break; 296 case 'I': /* multicast interface */ 297 if (inet_aton(optarg, &ifaddr) == 0) 298 errx(EX_USAGE, 299 "invalid multicast interface: `%s'", 300 optarg); 301 options |= F_MIF; 302 break; 303 case 'l': 304 ultmp = strtoul(optarg, &ep, 0); 305 if (*ep || ep == optarg || ultmp > INT_MAX) 306 errx(EX_USAGE, 307 "invalid preload value: `%s'", optarg); 308 if (uid) { 309 errno = EPERM; 310 err(EX_NOPERM, "-l flag"); 311 } 312 preload = ultmp; 313 break; 314 case 'L': 315 options |= F_NOLOOP; 316 loop = 0; 317 break; 318 case 'm': /* TTL */ 319 ultmp = strtoul(optarg, &ep, 0); 320 if (*ep || ep == optarg || ultmp > 255) 321 errx(EX_USAGE, "invalid TTL: `%s'", 322 optarg); 323 ttl = ultmp; 324 options |= F_TTL; 325 break; 326 case 'n': 327 options |= F_NUMERIC; 328 break; 329 case 'p': /* fill buffer with user pattern */ 330 options |= F_PINGFILLED; 331 fill((char *)datap, optarg); 332 break; 333 case 'Q': 334 options |= F_QUIET2; 335 break; 336 case 'q': 337 options |= F_QUIET; 338 break; 339 case 'R': 340 options |= F_RROUTE; 341 break; 342 case 'r': 343 options |= F_SO_DONTROUTE; 344 break; 345 case 's': /* size of packet to send */ 346 if (uid) { 347 errno = EPERM; 348 err(EX_NOPERM, "-s flag"); 349 } 350 ultmp = strtoul(optarg, &ep, 0); 351 if (ultmp > MAXPACKET) 352 errx(EX_USAGE, "packet size too large: %lu", 353 ultmp); 354 if (*ep || ep == optarg || !ultmp) 355 errx(EX_USAGE, "invalid packet size: `%s'", 356 optarg); 357 datalen = ultmp; 358 break; 359 case 'S': 360 source = optarg; 361 break; 362 case 't': 363 alarmtimeout = strtoul(optarg, &ep, 0); 364 if ((alarmtimeout < 1) || (alarmtimeout == ULONG_MAX)) 365 errx(EX_USAGE, "invalid timeout: `%s'", 366 optarg); 367 if (alarmtimeout > MAXALARM) 368 errx(EX_USAGE, "invalid timeout: `%s' > %d", 369 optarg, MAXALARM); 370 alarm((int)alarmtimeout); 371 break; 372 case 'T': /* multicast TTL */ 373 ultmp = strtoul(optarg, &ep, 0); 374 if (*ep || ep == optarg || ultmp > 255) 375 errx(EX_USAGE, "invalid multicast TTL: `%s'", 376 optarg); 377 mttl = ultmp; 378 options |= F_MTTL; 379 break; 380 case 'v': 381 options |= F_VERBOSE; 382 break; 383 #ifdef IPSEC 384 #ifdef IPSEC_POLICY_IPSEC 385 case 'P': 386 options |= F_POLICY; 387 if (!strncmp("in", optarg, 2)) 388 policy_in = strdup(optarg); 389 else if (!strncmp("out", optarg, 3)) 390 policy_out = strdup(optarg); 391 else 392 errx(1, "invalid security policy"); 393 break; 394 #endif /*IPSEC_POLICY_IPSEC*/ 395 #endif /*IPSEC*/ 396 default: 397 usage(); 398 } 399 } 400 401 if (argc - optind != 1) 402 usage(); 403 target = argv[optind]; 404 405 if (source) { 406 bzero((char *)&sin, sizeof(sin)); 407 sin.sin_family = AF_INET; 408 if (inet_aton(source, &sin.sin_addr) != 0) { 409 shostname = source; 410 } else { 411 hp = gethostbyname2(source, AF_INET); 412 if (!hp) 413 errx(EX_NOHOST, "cannot resolve %s: %s", 414 source, hstrerror(h_errno)); 415 416 sin.sin_len = sizeof sin; 417 if (hp->h_length > sizeof(sin.sin_addr)) 418 errx(1,"gethostbyname2: illegal address"); 419 memcpy(&sin.sin_addr, hp->h_addr_list[0], 420 sizeof (sin.sin_addr)); 421 (void)strncpy(snamebuf, hp->h_name, 422 sizeof(snamebuf) - 1); 423 snamebuf[sizeof(snamebuf) - 1] = '\0'; 424 shostname = snamebuf; 425 } 426 if (bind(s, (struct sockaddr *)&sin, sizeof sin) == -1) 427 err(1, "bind"); 428 } 429 430 bzero(&whereto, sizeof(whereto)); 431 to = &whereto; 432 to->sin_family = AF_INET; 433 to->sin_len = sizeof *to; 434 if (inet_aton(target, &to->sin_addr) != 0) { 435 hostname = target; 436 } else { 437 hp = gethostbyname2(target, AF_INET); 438 if (!hp) 439 errx(EX_NOHOST, "cannot resolve %s: %s", 440 target, hstrerror(h_errno)); 441 442 if (hp->h_length > sizeof(to->sin_addr)) 443 errx(1,"gethostbyname2 returned an illegal address"); 444 memcpy(&to->sin_addr, hp->h_addr_list[0], sizeof to->sin_addr); 445 (void)strncpy(hnamebuf, hp->h_name, sizeof(hnamebuf) - 1); 446 hnamebuf[sizeof(hnamebuf) - 1] = '\0'; 447 hostname = hnamebuf; 448 } 449 450 if (options & F_FLOOD && options & F_INTERVAL) 451 errx(EX_USAGE, "-f and -i: incompatible options"); 452 453 if (options & F_FLOOD && IN_MULTICAST(ntohl(to->sin_addr.s_addr))) 454 errx(EX_USAGE, 455 "-f flag cannot be used with multicast destination"); 456 if (options & (F_MIF | F_NOLOOP | F_MTTL) 457 && !IN_MULTICAST(ntohl(to->sin_addr.s_addr))) 458 errx(EX_USAGE, 459 "-I, -L, -T flags cannot be used with unicast destination"); 460 461 if (datalen >= PHDR_LEN) /* can we time transfer */ 462 timing = 1; 463 packlen = datalen + MAXIPLEN + MAXICMPLEN; 464 if (!(packet = (u_char *)malloc((size_t)packlen))) 465 err(EX_UNAVAILABLE, "malloc"); 466 467 if (!(options & F_PINGFILLED)) 468 for (i = PHDR_LEN; i < datalen; ++i) 469 *datap++ = i; 470 471 ident = getpid() & 0xFFFF; 472 473 if (s < 0) { 474 errno = sockerrno; 475 err(EX_OSERR, "socket"); 476 } 477 hold = 1; 478 if (options & F_SO_DEBUG) 479 (void)setsockopt(s, SOL_SOCKET, SO_DEBUG, (char *)&hold, 480 sizeof(hold)); 481 if (options & F_SO_DONTROUTE) 482 (void)setsockopt(s, SOL_SOCKET, SO_DONTROUTE, (char *)&hold, 483 sizeof(hold)); 484 #ifdef IPSEC 485 #ifdef IPSEC_POLICY_IPSEC 486 if (options & F_POLICY) { 487 char *buf; 488 if (policy_in != NULL) { 489 buf = ipsec_set_policy(policy_in, strlen(policy_in)); 490 if (buf == NULL) 491 errx(EX_CONFIG, "%s", ipsec_strerror()); 492 if (setsockopt(s, IPPROTO_IP, IP_IPSEC_POLICY, 493 buf, ipsec_get_policylen(buf)) < 0) 494 err(EX_CONFIG, "ipsec policy cannot be configured"); 495 free(buf); 496 } 497 498 if (policy_out != NULL) { 499 buf = ipsec_set_policy(policy_out, strlen(policy_out)); 500 if (buf == NULL) 501 errx(EX_CONFIG, "%s", ipsec_strerror()); 502 if (setsockopt(s, IPPROTO_IP, IP_IPSEC_POLICY, 503 buf, ipsec_get_policylen(buf)) < 0) 504 err(EX_CONFIG, "ipsec policy cannot be configured"); 505 free(buf); 506 } 507 } 508 #endif /*IPSEC_POLICY_IPSEC*/ 509 #endif /*IPSEC*/ 510 511 /* record route option */ 512 if (options & F_RROUTE) { 513 #ifdef IP_OPTIONS 514 bzero(rspace, sizeof(rspace)); 515 rspace[IPOPT_OPTVAL] = IPOPT_RR; 516 rspace[IPOPT_OLEN] = sizeof(rspace) - 1; 517 rspace[IPOPT_OFFSET] = IPOPT_MINOFF; 518 rspace[sizeof(rspace) - 1] = IPOPT_EOL; 519 if (setsockopt(s, IPPROTO_IP, IP_OPTIONS, rspace, 520 sizeof(rspace)) < 0) 521 err(EX_OSERR, "setsockopt IP_OPTIONS"); 522 #else 523 errx(EX_UNAVAILABLE, 524 "record route not available in this implementation"); 525 #endif /* IP_OPTIONS */ 526 } 527 528 if (options & F_TTL) { 529 if (setsockopt(s, IPPROTO_IP, IP_TTL, &ttl, 530 sizeof(ttl)) < 0) { 531 err(EX_OSERR, "setsockopt IP_TTL"); 532 } 533 } 534 if (options & F_NOLOOP) { 535 if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_LOOP, &loop, 536 sizeof(loop)) < 0) { 537 err(EX_OSERR, "setsockopt IP_MULTICAST_LOOP"); 538 } 539 } 540 if (options & F_MTTL) { 541 if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL, &mttl, 542 sizeof(mttl)) < 0) { 543 err(EX_OSERR, "setsockopt IP_MULTICAST_TTL"); 544 } 545 } 546 if (options & F_MIF) { 547 if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_IF, &ifaddr, 548 sizeof(ifaddr)) < 0) { 549 err(EX_OSERR, "setsockopt IP_MULTICAST_IF"); 550 } 551 } 552 #ifdef SO_TIMESTAMP 553 { int on = 1; 554 if (setsockopt(s, SOL_SOCKET, SO_TIMESTAMP, &on, sizeof(on)) < 0) 555 err(EX_OSERR, "setsockopt SO_TIMESTAMP"); 556 } 557 #endif 558 559 /* 560 * When pinging the broadcast address, you can get a lot of answers. 561 * Doing something so evil is useful if you are trying to stress the 562 * ethernet, or just want to fill the arp cache to get some stuff for 563 * /etc/ethers. But beware: RFC 1122 allows hosts to ignore broadcast 564 * or multicast pings if they wish. 565 */ 566 hold = 48 * 1024; 567 (void)setsockopt(s, SOL_SOCKET, SO_RCVBUF, (char *)&hold, 568 sizeof(hold)); 569 570 if (!uid) { 571 (void)setsockopt(s, SOL_SOCKET, SO_SNDBUF, (char *)&hold, 572 sizeof(hold)); 573 } 574 575 if (to->sin_family == AF_INET) { 576 (void)printf("PING %s (%s)", hostname, 577 inet_ntoa(to->sin_addr)); 578 if (source) 579 (void)printf(" from %s", shostname); 580 (void)printf(": %d data bytes\n", datalen); 581 } else 582 (void)printf("PING %s: %d data bytes\n", hostname, datalen); 583 584 /* 585 * Use sigaction() instead of signal() to get unambiguous semantics, 586 * in particular with SA_RESTART not set. 587 */ 588 589 sigemptyset(&si_sa.sa_mask); 590 si_sa.sa_flags = 0; 591 592 si_sa.sa_handler = stopit; 593 if (sigaction(SIGINT, &si_sa, 0) == -1) { 594 err(EX_OSERR, "sigaction SIGINT"); 595 } 596 597 si_sa.sa_handler = status; 598 if (sigaction(SIGINFO, &si_sa, 0) == -1) { 599 err(EX_OSERR, "sigaction"); 600 } 601 602 if (alarmtimeout > 0) { 603 si_sa.sa_handler = stopit; 604 if (sigaction(SIGALRM, &si_sa, 0) == -1) 605 err(EX_OSERR, "sigaction SIGALRM"); 606 } 607 608 bzero(&msg, sizeof(msg)); 609 msg.msg_name = (caddr_t)&from; 610 msg.msg_iov = &iov; 611 msg.msg_iovlen = 1; 612 #ifdef SO_TIMESTAMP 613 msg.msg_control = (caddr_t)ctrl; 614 #endif 615 iov.iov_base = packet; 616 iov.iov_len = packlen; 617 618 if (tcgetattr(STDOUT_FILENO, &ts) != -1) { 619 reset_kerninfo = !(ts.c_lflag & NOKERNINFO); 620 ts.c_lflag |= NOKERNINFO; 621 tcsetattr(STDOUT_FILENO, TCSANOW, &ts); 622 } 623 624 if (preload == 0) 625 pinger(); /* send the first ping */ 626 else { 627 if (npackets != 0 && preload > npackets) 628 preload = npackets; 629 while (preload--) /* fire off them quickies */ 630 pinger(); 631 } 632 (void)gettimeofday(&last, NULL); 633 634 if (options & F_FLOOD) { 635 intvl.tv_sec = 0; 636 intvl.tv_usec = 10000; 637 } else { 638 intvl.tv_sec = interval / 1000; 639 intvl.tv_usec = interval % 1000 * 1000; 640 } 641 642 while (!finish_up) { 643 int cc; 644 int n; 645 struct timeval timeout, now; 646 fd_set rfds; 647 648 check_status(); 649 FD_ZERO(&rfds); 650 FD_SET(s, &rfds); 651 (void)gettimeofday(&now, NULL); 652 timeout.tv_sec = last.tv_sec + intvl.tv_sec - now.tv_sec; 653 timeout.tv_usec = last.tv_usec + intvl.tv_usec - now.tv_usec; 654 while (timeout.tv_usec < 0) { 655 timeout.tv_usec += 1000000; 656 timeout.tv_sec--; 657 } 658 while (timeout.tv_usec >= 1000000) { 659 timeout.tv_usec -= 1000000; 660 timeout.tv_sec++; 661 } 662 if (timeout.tv_sec < 0) 663 timeout.tv_sec = timeout.tv_usec = 0; 664 n = select(s + 1, &rfds, NULL, NULL, &timeout); 665 if (n < 0) 666 continue; /* Must be EINTR. */ 667 if (n == 1) { 668 struct timeval *t = 0; 669 #ifdef SO_TIMESTAMP 670 struct cmsghdr *cmsg = (struct cmsghdr *)&ctrl; 671 672 msg.msg_controllen = sizeof(ctrl); 673 #endif 674 msg.msg_namelen = sizeof(from); 675 if ((cc = recvmsg(s, &msg, 0)) < 0) { 676 if (errno == EINTR) 677 continue; 678 warn("recvmsg"); 679 continue; 680 } 681 #ifdef SO_TIMESTAMP 682 if (cmsg->cmsg_level == SOL_SOCKET && 683 cmsg->cmsg_type == SCM_TIMESTAMP && 684 cmsg->cmsg_len == CMSG_LEN(sizeof *t)) { 685 /* Copy to avoid alignment problems: */ 686 memcpy(&now,CMSG_DATA(cmsg),sizeof(now)); 687 t = &now; 688 } 689 #endif 690 if (t == 0) { 691 (void)gettimeofday(&now, NULL); 692 t = &now; 693 } 694 pr_pack((char *)packet, cc, &from, t); 695 if (npackets && nreceived >= npackets) 696 break; 697 } 698 if (n == 0 || options & F_FLOOD) { 699 if (!npackets || ntransmitted < npackets) 700 pinger(); 701 else { 702 if (almost_done) 703 break; 704 almost_done = 1; 705 intvl.tv_usec = 0; 706 if (nreceived) { 707 intvl.tv_sec = 2 * tmax / 1000; 708 if (!intvl.tv_sec) 709 intvl.tv_sec = 1; 710 } else 711 intvl.tv_sec = MAXWAIT; 712 } 713 (void)gettimeofday(&last, NULL); 714 715 if (ntransmitted - nreceived - 1 > nmissedmax) { 716 nmissedmax = ntransmitted - nreceived - 1; 717 if (options & F_MISSED) 718 (void)write(STDOUT_FILENO, &BBELL, 1); 719 } 720 } 721 } 722 finish(); 723 /* NOTREACHED */ 724 exit(0); /* Make the compiler happy */ 725 } 726 727 /* 728 * stopit -- 729 * Set the global bit that causes the main loop to quit. 730 * Do NOT call finish() from here, since finish() does far too much 731 * to be called from a signal handler. 732 */ 733 void 734 stopit(sig) 735 int sig; 736 { 737 738 finish_up = 1; 739 } 740 741 /* 742 * pinger -- 743 * Compose and transmit an ICMP ECHO REQUEST packet. The IP packet 744 * will be added on by the kernel. The ID field is our UNIX process ID, 745 * and the sequence number is an ascending integer. The first 8 bytes 746 * of the data portion are used to hold a UNIX "timeval" struct in host 747 * byte-order, to compute the round-trip time. 748 */ 749 static void 750 pinger(void) 751 { 752 struct icmp *icp; 753 int cc, i; 754 755 icp = (struct icmp *)outpack; 756 icp->icmp_type = ICMP_ECHO; 757 icp->icmp_code = 0; 758 icp->icmp_cksum = 0; 759 icp->icmp_seq = htons(ntransmitted); 760 icp->icmp_id = ident; /* ID */ 761 762 CLR(ntransmitted % mx_dup_ck); 763 764 if (timing) 765 (void)gettimeofday((struct timeval *)&outpack[8], 766 (struct timezone *)NULL); 767 768 cc = datalen + PHDR_LEN; /* skips ICMP portion */ 769 770 /* compute ICMP checksum here */ 771 icp->icmp_cksum = in_cksum((u_short *)icp, cc); 772 773 i = sendto(s, (char *)outpack, cc, 0, (struct sockaddr *)&whereto, 774 sizeof(whereto)); 775 776 if (i < 0 || i != cc) { 777 if (i < 0) { 778 if (options & F_FLOOD && errno == ENOBUFS) { 779 usleep(FLOOD_BACKOFF); 780 return; 781 } 782 warn("sendto"); 783 } else { 784 warn("%s: partial write: %d of %d bytes", 785 hostname, i, cc); 786 } 787 } 788 ntransmitted++; 789 if (!(options & F_QUIET) && options & F_FLOOD) 790 (void)write(STDOUT_FILENO, &DOT, 1); 791 } 792 793 /* 794 * pr_pack -- 795 * Print out the packet, if it came from us. This logic is necessary 796 * because ALL readers of the ICMP socket get a copy of ALL ICMP packets 797 * which arrive ('tis only fair). This permits multiple copies of this 798 * program to be run without having intermingled output (or statistics!). 799 */ 800 static void 801 pr_pack(buf, cc, from, tv) 802 char *buf; 803 int cc; 804 struct sockaddr_in *from; 805 struct timeval *tv; 806 { 807 struct icmp *icp; 808 struct ip *ip; 809 struct timeval *tp; 810 u_char *cp, *dp; 811 double triptime; 812 u_long l; 813 int dupflag, hlen, i, j, seq; 814 static int old_rrlen; 815 static char old_rr[MAX_IPOPTLEN]; 816 817 /* Check the IP header */ 818 ip = (struct ip *)buf; 819 hlen = ip->ip_hl << 2; 820 if (cc < hlen + ICMP_MINLEN) { 821 if (options & F_VERBOSE) 822 warn("packet too short (%d bytes) from %s", cc, 823 inet_ntoa(from->sin_addr)); 824 return; 825 } 826 827 /* Now the ICMP part */ 828 cc -= hlen; 829 icp = (struct icmp *)(buf + hlen); 830 if (icp->icmp_type == ICMP_ECHOREPLY) { 831 if (icp->icmp_id != ident) 832 return; /* 'Twas not our ECHO */ 833 ++nreceived; 834 triptime = 0.0; 835 if (timing) { 836 struct timeval tv1; 837 #ifndef icmp_data 838 tp = (struct timeval *)&icp->icmp_ip; 839 #else 840 tp = (struct timeval *)icp->icmp_data; 841 #endif 842 /* Avoid unaligned data: */ 843 memcpy(&tv1,tp,sizeof(tv1)); 844 tvsub(tv, &tv1); 845 triptime = ((double)tv->tv_sec) * 1000.0 + 846 ((double)tv->tv_usec) / 1000.0; 847 tsum += triptime; 848 tsumsq += triptime * triptime; 849 if (triptime < tmin) 850 tmin = triptime; 851 if (triptime > tmax) 852 tmax = triptime; 853 } 854 855 seq = ntohs(icp->icmp_seq); 856 857 if (TST(seq % mx_dup_ck)) { 858 ++nrepeats; 859 --nreceived; 860 dupflag = 1; 861 } else { 862 SET(seq % mx_dup_ck); 863 dupflag = 0; 864 } 865 866 if (options & F_QUIET) 867 return; 868 869 if (options & F_FLOOD) 870 (void)write(STDOUT_FILENO, &BSPACE, 1); 871 else { 872 (void)printf("%d bytes from %s: icmp_seq=%u", cc, 873 inet_ntoa(*(struct in_addr *)&from->sin_addr.s_addr), 874 seq); 875 (void)printf(" ttl=%d", ip->ip_ttl); 876 if (timing) 877 (void)printf(" time=%.3f ms", triptime); 878 if (dupflag) 879 (void)printf(" (DUP!)"); 880 if (options & F_AUDIBLE) 881 (void)write(STDOUT_FILENO, &BBELL, 1); 882 /* check the data */ 883 cp = (u_char*)&icp->icmp_data[PHDR_LEN]; 884 dp = &outpack[8 + PHDR_LEN]; 885 for (i = PHDR_LEN; i < datalen; ++i, ++cp, ++dp) { 886 if (*cp != *dp) { 887 (void)printf("\nwrong data byte #%d should be 0x%x but was 0x%x", 888 i, *dp, *cp); 889 printf("\ncp:"); 890 cp = (u_char*)&icp->icmp_data[0]; 891 for (i = 0; i < datalen; ++i, ++cp) { 892 if ((i % 32) == 8) 893 (void)printf("\n\t"); 894 (void)printf("%x ", *cp); 895 } 896 printf("\ndp:"); 897 cp = &outpack[8]; 898 for (i = 0; i < datalen; ++i, ++cp) { 899 if ((i % 32) == 8) 900 (void)printf("\n\t"); 901 (void)printf("%x ", *cp); 902 } 903 break; 904 } 905 } 906 } 907 } else { 908 /* 909 * We've got something other than an ECHOREPLY. 910 * See if it's a reply to something that we sent. 911 * We can compare IP destination, protocol, 912 * and ICMP type and ID. 913 * 914 * Only print all the error messages if we are running 915 * as root to avoid leaking information not normally 916 * available to those not running as root. 917 */ 918 #ifndef icmp_data 919 struct ip *oip = &icp->icmp_ip; 920 #else 921 struct ip *oip = (struct ip *)icp->icmp_data; 922 #endif 923 struct icmp *oicmp = (struct icmp *)(oip + 1); 924 925 if (((options & F_VERBOSE) && uid == 0) || 926 (!(options & F_QUIET2) && 927 (oip->ip_dst.s_addr == whereto.sin_addr.s_addr) && 928 (oip->ip_p == IPPROTO_ICMP) && 929 (oicmp->icmp_type == ICMP_ECHO) && 930 (oicmp->icmp_id == ident))) { 931 (void)printf("%d bytes from %s: ", cc, 932 pr_addr(from->sin_addr)); 933 pr_icmph(icp); 934 } else 935 return; 936 } 937 938 /* Display any IP options */ 939 cp = (u_char *)buf + sizeof(struct ip); 940 941 for (; hlen > (int)sizeof(struct ip); --hlen, ++cp) 942 switch (*cp) { 943 case IPOPT_EOL: 944 hlen = 0; 945 break; 946 case IPOPT_LSRR: 947 (void)printf("\nLSRR: "); 948 hlen -= 2; 949 j = *++cp; 950 ++cp; 951 if (j > IPOPT_MINOFF) 952 for (;;) { 953 l = *++cp; 954 l = (l<<8) + *++cp; 955 l = (l<<8) + *++cp; 956 l = (l<<8) + *++cp; 957 if (l == 0) { 958 printf("\t0.0.0.0"); 959 } else { 960 struct in_addr ina; 961 ina.s_addr = ntohl(l); 962 printf("\t%s", pr_addr(ina)); 963 } 964 hlen -= 4; 965 j -= 4; 966 if (j <= IPOPT_MINOFF) 967 break; 968 (void)putchar('\n'); 969 } 970 break; 971 case IPOPT_RR: 972 j = *++cp; /* get length */ 973 i = *++cp; /* and pointer */ 974 hlen -= 2; 975 if (i > j) 976 i = j; 977 i -= IPOPT_MINOFF; 978 if (i <= 0) 979 continue; 980 if (i == old_rrlen 981 && cp == (u_char *)buf + sizeof(struct ip) + 2 982 && !bcmp((char *)cp, old_rr, i) 983 && !(options & F_FLOOD)) { 984 (void)printf("\t(same route)"); 985 i = ((i + 3) / 4) * 4; 986 hlen -= i; 987 cp += i; 988 break; 989 } 990 if (i < MAX_IPOPTLEN) { 991 old_rrlen = i; 992 bcopy((char *)cp, old_rr, i); 993 } else 994 old_rrlen = 0; 995 996 (void)printf("\nRR: "); 997 j = 0; 998 for (;;) { 999 l = *++cp; 1000 l = (l<<8) + *++cp; 1001 l = (l<<8) + *++cp; 1002 l = (l<<8) + *++cp; 1003 if (l == 0) { 1004 printf("\t0.0.0.0"); 1005 } else { 1006 struct in_addr ina; 1007 ina.s_addr = ntohl(l); 1008 printf("\t%s", pr_addr(ina)); 1009 } 1010 hlen -= 4; 1011 i -= 4; 1012 j += 4; 1013 if (i <= 0) 1014 break; 1015 if (j >= MAX_IPOPTLEN) { 1016 (void) printf("\t(truncated route)"); 1017 break; 1018 } 1019 (void)putchar('\n'); 1020 } 1021 break; 1022 case IPOPT_NOP: 1023 (void)printf("\nNOP"); 1024 break; 1025 default: 1026 (void)printf("\nunknown option %x", *cp); 1027 break; 1028 } 1029 if (!(options & F_FLOOD)) { 1030 (void)putchar('\n'); 1031 (void)fflush(stdout); 1032 } 1033 } 1034 1035 /* 1036 * in_cksum -- 1037 * Checksum routine for Internet Protocol family headers (C Version) 1038 */ 1039 u_short 1040 in_cksum(addr, len) 1041 u_short *addr; 1042 int len; 1043 { 1044 int nleft, sum; 1045 u_short *w; 1046 union { 1047 u_short us; 1048 u_char uc[2]; 1049 } last; 1050 u_short answer; 1051 1052 nleft = len; 1053 sum = 0; 1054 w = addr; 1055 1056 /* 1057 * Our algorithm is simple, using a 32 bit accumulator (sum), we add 1058 * sequential 16 bit words to it, and at the end, fold back all the 1059 * carry bits from the top 16 bits into the lower 16 bits. 1060 */ 1061 while (nleft > 1) { 1062 sum += *w++; 1063 nleft -= 2; 1064 } 1065 1066 /* mop up an odd byte, if necessary */ 1067 if (nleft == 1) { 1068 last.uc[0] = *(u_char *)w; 1069 last.uc[1] = 0; 1070 sum += last.us; 1071 } 1072 1073 /* add back carry outs from top 16 bits to low 16 bits */ 1074 sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */ 1075 sum += (sum >> 16); /* add carry */ 1076 answer = ~sum; /* truncate to 16 bits */ 1077 return(answer); 1078 } 1079 1080 /* 1081 * tvsub -- 1082 * Subtract 2 timeval structs: out = out - in. Out is assumed to 1083 * be >= in. 1084 */ 1085 static void 1086 tvsub(out, in) 1087 struct timeval *out, *in; 1088 { 1089 1090 if ((out->tv_usec -= in->tv_usec) < 0) { 1091 --out->tv_sec; 1092 out->tv_usec += 1000000; 1093 } 1094 out->tv_sec -= in->tv_sec; 1095 } 1096 1097 /* 1098 * status -- 1099 * Print out statistics when SIGINFO is received. 1100 */ 1101 1102 static void 1103 status(sig) 1104 int sig; 1105 { 1106 1107 siginfo_p = 1; 1108 } 1109 1110 static void 1111 check_status() 1112 { 1113 1114 if (siginfo_p) { 1115 siginfo_p = 0; 1116 (void)fprintf(stderr, 1117 "\r%ld/%ld packets received (%.0f%%) %.3f min / %.3f avg / %.3f max\n", 1118 nreceived, ntransmitted, 1119 ntransmitted ? nreceived * 100.0 / ntransmitted : 0.0, 1120 nreceived ? tmin : 0.0, 1121 nreceived + nrepeats ? tsum / (nreceived + nrepeats) : tsum, 1122 tmax); 1123 } 1124 } 1125 1126 /* 1127 * finish -- 1128 * Print out statistics, and give up. 1129 */ 1130 static void 1131 finish() 1132 { 1133 1134 struct termios ts; 1135 1136 (void)signal(SIGINT, SIG_IGN); 1137 (void)signal(SIGALRM, SIG_IGN); 1138 (void)putchar('\n'); 1139 (void)fflush(stdout); 1140 (void)printf("--- %s ping statistics ---\n", hostname); 1141 (void)printf("%ld packets transmitted, ", ntransmitted); 1142 (void)printf("%ld packets received, ", nreceived); 1143 if (nrepeats) 1144 (void)printf("+%ld duplicates, ", nrepeats); 1145 if (ntransmitted) { 1146 if (nreceived > ntransmitted) 1147 (void)printf("-- somebody's printing up packets!"); 1148 else 1149 (void)printf("%d%% packet loss", 1150 (int) (((ntransmitted - nreceived) * 100) / 1151 ntransmitted)); 1152 } 1153 (void)putchar('\n'); 1154 if (nreceived && timing) { 1155 double n = nreceived + nrepeats; 1156 double avg = tsum / n; 1157 double vari = tsumsq / n - avg * avg; 1158 printf("round-trip min/avg/max/stddev = " 1159 "%.3f/%.3f/%.3f/%.3f ms\n", 1160 tmin, avg, tmax, sqrt(vari)); 1161 } 1162 if (reset_kerninfo && tcgetattr(STDOUT_FILENO, &ts) != -1) { 1163 ts.c_lflag &= ~NOKERNINFO; 1164 tcsetattr(STDOUT_FILENO, TCSANOW, &ts); 1165 } 1166 1167 if (nreceived) 1168 exit(0); 1169 else 1170 exit(2); 1171 } 1172 1173 #ifdef notdef 1174 static char *ttab[] = { 1175 "Echo Reply", /* ip + seq + udata */ 1176 "Dest Unreachable", /* net, host, proto, port, frag, sr + IP */ 1177 "Source Quench", /* IP */ 1178 "Redirect", /* redirect type, gateway, + IP */ 1179 "Echo", 1180 "Time Exceeded", /* transit, frag reassem + IP */ 1181 "Parameter Problem", /* pointer + IP */ 1182 "Timestamp", /* id + seq + three timestamps */ 1183 "Timestamp Reply", /* " */ 1184 "Info Request", /* id + sq */ 1185 "Info Reply" /* " */ 1186 }; 1187 #endif 1188 1189 /* 1190 * pr_icmph -- 1191 * Print a descriptive string about an ICMP header. 1192 */ 1193 static void 1194 pr_icmph(icp) 1195 struct icmp *icp; 1196 { 1197 1198 switch(icp->icmp_type) { 1199 case ICMP_ECHOREPLY: 1200 (void)printf("Echo Reply\n"); 1201 /* XXX ID + Seq + Data */ 1202 break; 1203 case ICMP_UNREACH: 1204 switch(icp->icmp_code) { 1205 case ICMP_UNREACH_NET: 1206 (void)printf("Destination Net Unreachable\n"); 1207 break; 1208 case ICMP_UNREACH_HOST: 1209 (void)printf("Destination Host Unreachable\n"); 1210 break; 1211 case ICMP_UNREACH_PROTOCOL: 1212 (void)printf("Destination Protocol Unreachable\n"); 1213 break; 1214 case ICMP_UNREACH_PORT: 1215 (void)printf("Destination Port Unreachable\n"); 1216 break; 1217 case ICMP_UNREACH_NEEDFRAG: 1218 (void)printf("frag needed and DF set (MTU %d)\n", 1219 ntohs(icp->icmp_nextmtu)); 1220 break; 1221 case ICMP_UNREACH_SRCFAIL: 1222 (void)printf("Source Route Failed\n"); 1223 break; 1224 case ICMP_UNREACH_FILTER_PROHIB: 1225 (void)printf("Communication prohibited by filter\n"); 1226 break; 1227 default: 1228 (void)printf("Dest Unreachable, Bad Code: %d\n", 1229 icp->icmp_code); 1230 break; 1231 } 1232 /* Print returned IP header information */ 1233 #ifndef icmp_data 1234 pr_retip(&icp->icmp_ip); 1235 #else 1236 pr_retip((struct ip *)icp->icmp_data); 1237 #endif 1238 break; 1239 case ICMP_SOURCEQUENCH: 1240 (void)printf("Source Quench\n"); 1241 #ifndef icmp_data 1242 pr_retip(&icp->icmp_ip); 1243 #else 1244 pr_retip((struct ip *)icp->icmp_data); 1245 #endif 1246 break; 1247 case ICMP_REDIRECT: 1248 switch(icp->icmp_code) { 1249 case ICMP_REDIRECT_NET: 1250 (void)printf("Redirect Network"); 1251 break; 1252 case ICMP_REDIRECT_HOST: 1253 (void)printf("Redirect Host"); 1254 break; 1255 case ICMP_REDIRECT_TOSNET: 1256 (void)printf("Redirect Type of Service and Network"); 1257 break; 1258 case ICMP_REDIRECT_TOSHOST: 1259 (void)printf("Redirect Type of Service and Host"); 1260 break; 1261 default: 1262 (void)printf("Redirect, Bad Code: %d", icp->icmp_code); 1263 break; 1264 } 1265 (void)printf("(New addr: %s)\n", inet_ntoa(icp->icmp_gwaddr)); 1266 #ifndef icmp_data 1267 pr_retip(&icp->icmp_ip); 1268 #else 1269 pr_retip((struct ip *)icp->icmp_data); 1270 #endif 1271 break; 1272 case ICMP_ECHO: 1273 (void)printf("Echo Request\n"); 1274 /* XXX ID + Seq + Data */ 1275 break; 1276 case ICMP_TIMXCEED: 1277 switch(icp->icmp_code) { 1278 case ICMP_TIMXCEED_INTRANS: 1279 (void)printf("Time to live exceeded\n"); 1280 break; 1281 case ICMP_TIMXCEED_REASS: 1282 (void)printf("Frag reassembly time exceeded\n"); 1283 break; 1284 default: 1285 (void)printf("Time exceeded, Bad Code: %d\n", 1286 icp->icmp_code); 1287 break; 1288 } 1289 #ifndef icmp_data 1290 pr_retip(&icp->icmp_ip); 1291 #else 1292 pr_retip((struct ip *)icp->icmp_data); 1293 #endif 1294 break; 1295 case ICMP_PARAMPROB: 1296 (void)printf("Parameter problem: pointer = 0x%02x\n", 1297 icp->icmp_hun.ih_pptr); 1298 #ifndef icmp_data 1299 pr_retip(&icp->icmp_ip); 1300 #else 1301 pr_retip((struct ip *)icp->icmp_data); 1302 #endif 1303 break; 1304 case ICMP_TSTAMP: 1305 (void)printf("Timestamp\n"); 1306 /* XXX ID + Seq + 3 timestamps */ 1307 break; 1308 case ICMP_TSTAMPREPLY: 1309 (void)printf("Timestamp Reply\n"); 1310 /* XXX ID + Seq + 3 timestamps */ 1311 break; 1312 case ICMP_IREQ: 1313 (void)printf("Information Request\n"); 1314 /* XXX ID + Seq */ 1315 break; 1316 case ICMP_IREQREPLY: 1317 (void)printf("Information Reply\n"); 1318 /* XXX ID + Seq */ 1319 break; 1320 case ICMP_MASKREQ: 1321 (void)printf("Address Mask Request\n"); 1322 break; 1323 case ICMP_MASKREPLY: 1324 (void)printf("Address Mask Reply\n"); 1325 break; 1326 case ICMP_ROUTERADVERT: 1327 (void)printf("Router Advertisement\n"); 1328 break; 1329 case ICMP_ROUTERSOLICIT: 1330 (void)printf("Router Solicitation\n"); 1331 break; 1332 default: 1333 (void)printf("Bad ICMP type: %d\n", icp->icmp_type); 1334 } 1335 } 1336 1337 /* 1338 * pr_iph -- 1339 * Print an IP header with options. 1340 */ 1341 static void 1342 pr_iph(ip) 1343 struct ip *ip; 1344 { 1345 u_char *cp; 1346 int hlen; 1347 1348 hlen = ip->ip_hl << 2; 1349 cp = (u_char *)ip + 20; /* point to options */ 1350 1351 (void)printf("Vr HL TOS Len ID Flg off TTL Pro cks Src Dst\n"); 1352 (void)printf(" %1x %1x %02x %04x %04x", 1353 ip->ip_v, ip->ip_hl, ip->ip_tos, ntohs(ip->ip_len), 1354 ntohs(ip->ip_id)); 1355 (void)printf(" %1lx %04lx", 1356 (u_long) (ntohl(ip->ip_off) & 0xe000) >> 13, 1357 (u_long) ntohl(ip->ip_off) & 0x1fff); 1358 (void)printf(" %02x %02x %04x", ip->ip_ttl, ip->ip_p, 1359 ntohs(ip->ip_sum)); 1360 (void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_src.s_addr)); 1361 (void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_dst.s_addr)); 1362 /* dump any option bytes */ 1363 while (hlen-- > 20) { 1364 (void)printf("%02x", *cp++); 1365 } 1366 (void)putchar('\n'); 1367 } 1368 1369 /* 1370 * pr_addr -- 1371 * Return an ascii host address as a dotted quad and optionally with 1372 * a hostname. 1373 */ 1374 static char * 1375 pr_addr(ina) 1376 struct in_addr ina; 1377 { 1378 struct hostent *hp; 1379 static char buf[16 + 3 + MAXHOSTNAMELEN]; 1380 1381 if ((options & F_NUMERIC) || 1382 !(hp = gethostbyaddr((char *)&ina, 4, AF_INET))) 1383 return inet_ntoa(ina); 1384 else 1385 (void)snprintf(buf, sizeof(buf), "%s (%s)", hp->h_name, 1386 inet_ntoa(ina)); 1387 return(buf); 1388 } 1389 1390 /* 1391 * pr_retip -- 1392 * Dump some info on a returned (via ICMP) IP packet. 1393 */ 1394 static void 1395 pr_retip(ip) 1396 struct ip *ip; 1397 { 1398 u_char *cp; 1399 int hlen; 1400 1401 pr_iph(ip); 1402 hlen = ip->ip_hl << 2; 1403 cp = (u_char *)ip + hlen; 1404 1405 if (ip->ip_p == 6) 1406 (void)printf("TCP: from port %u, to port %u (decimal)\n", 1407 (*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3))); 1408 else if (ip->ip_p == 17) 1409 (void)printf("UDP: from port %u, to port %u (decimal)\n", 1410 (*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3))); 1411 } 1412 1413 static void 1414 fill(bp, patp) 1415 char *bp, *patp; 1416 { 1417 char *cp; 1418 int pat[16]; 1419 int ii, jj, kk; 1420 1421 for (cp = patp; *cp; cp++) { 1422 if (!isxdigit(*cp)) 1423 errx(EX_USAGE, 1424 "patterns must be specified as hex digits"); 1425 1426 } 1427 ii = sscanf(patp, 1428 "%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x", 1429 &pat[0], &pat[1], &pat[2], &pat[3], &pat[4], &pat[5], &pat[6], 1430 &pat[7], &pat[8], &pat[9], &pat[10], &pat[11], &pat[12], 1431 &pat[13], &pat[14], &pat[15]); 1432 1433 if (ii > 0) 1434 for (kk = 0; 1435 kk <= MAXPACKET - (8 + PHDR_LEN + ii); 1436 kk += ii) 1437 for (jj = 0; jj < ii; ++jj) 1438 bp[jj + kk] = pat[jj]; 1439 if (!(options & F_QUIET)) { 1440 (void)printf("PATTERN: 0x"); 1441 for (jj = 0; jj < ii; ++jj) 1442 (void)printf("%02x", bp[jj] & 0xFF); 1443 (void)printf("\n"); 1444 } 1445 } 1446 1447 static void 1448 usage() 1449 { 1450 fprintf(stderr, "%s\n%s\n%s\n", 1451 "usage: ping [-QRadfnqrv] [-c count] [-i wait] [-l preload] [-m ttl]", 1452 " [-p pattern] " 1453 #ifdef IPSEC 1454 #ifdef IPSEC_POLICY_IPSEC 1455 "[-P policy] " 1456 #endif 1457 #endif 1458 "[-s packetsize] [-S src_addr] [-t timeout]", 1459 " [host | [-L] [-I iface] [-T ttl] mcast-group]"); 1460 exit(EX_USAGE); 1461 } 1462