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