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 while (preload--) /* fire off them quickies */ 624 pinger(); 625 626 if (options & F_FLOOD) { 627 intvl.tv_sec = 0; 628 intvl.tv_usec = 10000; 629 } else { 630 intvl.tv_sec = interval / 1000; 631 intvl.tv_usec = interval % 1000 * 1000; 632 } 633 634 pinger(); /* send the first ping */ 635 (void)gettimeofday(&last, NULL); 636 637 while (!finish_up) { 638 register int cc; 639 int n; 640 struct timeval timeout, now; 641 fd_set rfds; 642 643 check_status(); 644 FD_ZERO(&rfds); 645 FD_SET(s, &rfds); 646 (void)gettimeofday(&now, NULL); 647 timeout.tv_sec = last.tv_sec + intvl.tv_sec - now.tv_sec; 648 timeout.tv_usec = last.tv_usec + intvl.tv_usec - now.tv_usec; 649 while (timeout.tv_usec < 0) { 650 timeout.tv_usec += 1000000; 651 timeout.tv_sec--; 652 } 653 while (timeout.tv_usec >= 1000000) { 654 timeout.tv_usec -= 1000000; 655 timeout.tv_sec++; 656 } 657 if (timeout.tv_sec < 0) 658 timeout.tv_sec = timeout.tv_usec = 0; 659 n = select(s + 1, &rfds, NULL, NULL, &timeout); 660 if (n < 0) 661 continue; /* Must be EINTR. */ 662 if (n == 1) { 663 struct timeval *t = 0; 664 #ifdef SO_TIMESTAMP 665 struct cmsghdr *cmsg = (struct cmsghdr *)&ctrl; 666 667 msg.msg_controllen = sizeof(ctrl); 668 #endif 669 msg.msg_namelen = sizeof(from); 670 if ((cc = recvmsg(s, &msg, 0)) < 0) { 671 if (errno == EINTR) 672 continue; 673 warn("recvmsg"); 674 continue; 675 } 676 #ifdef SO_TIMESTAMP 677 if (cmsg->cmsg_level == SOL_SOCKET && 678 cmsg->cmsg_type == SCM_TIMESTAMP && 679 cmsg->cmsg_len == CMSG_LEN(sizeof *t)) { 680 /* Copy to avoid alignment problems: */ 681 memcpy(&now,CMSG_DATA(cmsg),sizeof(now)); 682 t = &now; 683 } 684 #endif 685 if (t == 0) { 686 (void)gettimeofday(&now, NULL); 687 t = &now; 688 } 689 pr_pack((char *)packet, cc, &from, t); 690 if (npackets && nreceived >= npackets) 691 break; 692 } 693 if (n == 0 || options & F_FLOOD) { 694 if (!npackets || ntransmitted < npackets) 695 pinger(); 696 else { 697 if (almost_done) 698 break; 699 almost_done = 1; 700 intvl.tv_usec = 0; 701 if (nreceived) { 702 intvl.tv_sec = 2 * tmax / 1000; 703 if (!intvl.tv_sec) 704 intvl.tv_sec = 1; 705 } else 706 intvl.tv_sec = MAXWAIT; 707 } 708 (void)gettimeofday(&last, NULL); 709 710 if (ntransmitted - nreceived - 1 > nmissedmax) { 711 nmissedmax = ntransmitted - nreceived - 1; 712 if (options & F_MISSED) 713 (void)write(STDOUT_FILENO, &BBELL, 1); 714 } 715 } 716 } 717 finish(); 718 /* NOTREACHED */ 719 exit(0); /* Make the compiler happy */ 720 } 721 722 /* 723 * stopit -- 724 * Set the global bit that causes the main loop to quit. 725 * Do NOT call finish() from here, since finish() does far too much 726 * to be called from a signal handler. 727 */ 728 void 729 stopit(sig) 730 int sig; 731 { 732 finish_up = 1; 733 } 734 735 /* 736 * pinger -- 737 * Compose and transmit an ICMP ECHO REQUEST packet. The IP packet 738 * will be added on by the kernel. The ID field is our UNIX process ID, 739 * and the sequence number is an ascending integer. The first 8 bytes 740 * of the data portion are used to hold a UNIX "timeval" struct in host 741 * byte-order, to compute the round-trip time. 742 */ 743 static void 744 pinger(void) 745 { 746 register struct icmp *icp; 747 register int cc; 748 int i; 749 750 icp = (struct icmp *)outpack; 751 icp->icmp_type = ICMP_ECHO; 752 icp->icmp_code = 0; 753 icp->icmp_cksum = 0; 754 icp->icmp_seq = ntransmitted; 755 icp->icmp_id = ident; /* ID */ 756 757 CLR(icp->icmp_seq % mx_dup_ck); 758 759 if (timing) 760 (void)gettimeofday((struct timeval *)&outpack[8], 761 (struct timezone *)NULL); 762 763 cc = datalen + PHDR_LEN; /* skips ICMP portion */ 764 765 /* compute ICMP checksum here */ 766 icp->icmp_cksum = in_cksum((u_short *)icp, cc); 767 768 i = sendto(s, (char *)outpack, cc, 0, (struct sockaddr *)&whereto, 769 sizeof(whereto)); 770 771 if (i < 0 || i != cc) { 772 if (i < 0) { 773 if (options & F_FLOOD && errno == ENOBUFS) { 774 usleep(FLOOD_BACKOFF); 775 return; 776 } 777 warn("sendto"); 778 } else { 779 warn("%s: partial write: %d of %d bytes", 780 hostname, i, cc); 781 } 782 } 783 ntransmitted++; 784 if (!(options & F_QUIET) && options & F_FLOOD) 785 (void)write(STDOUT_FILENO, &DOT, 1); 786 } 787 788 /* 789 * pr_pack -- 790 * Print out the packet, if it came from us. This logic is necessary 791 * because ALL readers of the ICMP socket get a copy of ALL ICMP packets 792 * which arrive ('tis only fair). This permits multiple copies of this 793 * program to be run without having intermingled output (or statistics!). 794 */ 795 static void 796 pr_pack(buf, cc, from, tv) 797 char *buf; 798 int cc; 799 struct sockaddr_in *from; 800 struct timeval *tv; 801 { 802 register struct icmp *icp; 803 register u_long l; 804 register int i, j; 805 register u_char *cp,*dp; 806 static int old_rrlen; 807 static char old_rr[MAX_IPOPTLEN]; 808 struct ip *ip; 809 struct timeval *tp; 810 double triptime; 811 int hlen, dupflag; 812 813 /* Check the IP header */ 814 ip = (struct ip *)buf; 815 hlen = ip->ip_hl << 2; 816 if (cc < hlen + ICMP_MINLEN) { 817 if (options & F_VERBOSE) 818 warn("packet too short (%d bytes) from %s", cc, 819 inet_ntoa(from->sin_addr)); 820 return; 821 } 822 823 /* Now the ICMP part */ 824 cc -= hlen; 825 icp = (struct icmp *)(buf + hlen); 826 if (icp->icmp_type == ICMP_ECHOREPLY) { 827 if (icp->icmp_id != ident) 828 return; /* 'Twas not our ECHO */ 829 ++nreceived; 830 triptime = 0.0; 831 if (timing) { 832 struct timeval tv1; 833 #ifndef icmp_data 834 tp = (struct timeval *)&icp->icmp_ip; 835 #else 836 tp = (struct timeval *)icp->icmp_data; 837 #endif 838 /* Avoid unaligned data: */ 839 memcpy(&tv1,tp,sizeof(tv1)); 840 tvsub(tv, &tv1); 841 triptime = ((double)tv->tv_sec) * 1000.0 + 842 ((double)tv->tv_usec) / 1000.0; 843 tsum += triptime; 844 tsumsq += triptime * triptime; 845 if (triptime < tmin) 846 tmin = triptime; 847 if (triptime > tmax) 848 tmax = triptime; 849 } 850 851 if (TST(icp->icmp_seq % mx_dup_ck)) { 852 ++nrepeats; 853 --nreceived; 854 dupflag = 1; 855 } else { 856 SET(icp->icmp_seq % mx_dup_ck); 857 dupflag = 0; 858 } 859 860 if (options & F_QUIET) 861 return; 862 863 if (options & F_FLOOD) 864 (void)write(STDOUT_FILENO, &BSPACE, 1); 865 else { 866 (void)printf("%d bytes from %s: icmp_seq=%u", cc, 867 inet_ntoa(*(struct in_addr *)&from->sin_addr.s_addr), 868 icp->icmp_seq); 869 (void)printf(" ttl=%d", ip->ip_ttl); 870 if (timing) 871 (void)printf(" time=%.3f ms", triptime); 872 if (dupflag) 873 (void)printf(" (DUP!)"); 874 if (options & F_AUDIBLE) 875 (void)write(STDOUT_FILENO, &BBELL, 1); 876 /* check the data */ 877 cp = (u_char*)&icp->icmp_data[PHDR_LEN]; 878 dp = &outpack[8 + PHDR_LEN]; 879 for (i = PHDR_LEN; i < datalen; ++i, ++cp, ++dp) { 880 if (*cp != *dp) { 881 (void)printf("\nwrong data byte #%d should be 0x%x but was 0x%x", 882 i, *dp, *cp); 883 printf("\ncp:"); 884 cp = (u_char*)&icp->icmp_data[0]; 885 for (i = 0; i < datalen; ++i, ++cp) { 886 if ((i % 32) == 8) 887 (void)printf("\n\t"); 888 (void)printf("%x ", *cp); 889 } 890 printf("\ndp:"); 891 cp = &outpack[8]; 892 for (i = 0; i < datalen; ++i, ++cp) { 893 if ((i % 32) == 8) 894 (void)printf("\n\t"); 895 (void)printf("%x ", *cp); 896 } 897 break; 898 } 899 } 900 } 901 } else { 902 /* 903 * We've got something other than an ECHOREPLY. 904 * See if it's a reply to something that we sent. 905 * We can compare IP destination, protocol, 906 * and ICMP type and ID. 907 * 908 * Only print all the error messages if we are running 909 * as root to avoid leaking information not normally 910 * available to those not running as root. 911 */ 912 #ifndef icmp_data 913 struct ip *oip = &icp->icmp_ip; 914 #else 915 struct ip *oip = (struct ip *)icp->icmp_data; 916 #endif 917 struct icmp *oicmp = (struct icmp *)(oip + 1); 918 919 if (((options & F_VERBOSE) && uid == 0) || 920 (!(options & F_QUIET2) && 921 (oip->ip_dst.s_addr == whereto.sin_addr.s_addr) && 922 (oip->ip_p == IPPROTO_ICMP) && 923 (oicmp->icmp_type == ICMP_ECHO) && 924 (oicmp->icmp_id == ident))) { 925 (void)printf("%d bytes from %s: ", cc, 926 pr_addr(from->sin_addr)); 927 pr_icmph(icp); 928 } else 929 return; 930 } 931 932 /* Display any IP options */ 933 cp = (u_char *)buf + sizeof(struct ip); 934 935 for (; hlen > (int)sizeof(struct ip); --hlen, ++cp) 936 switch (*cp) { 937 case IPOPT_EOL: 938 hlen = 0; 939 break; 940 case IPOPT_LSRR: 941 (void)printf("\nLSRR: "); 942 hlen -= 2; 943 j = *++cp; 944 ++cp; 945 if (j > IPOPT_MINOFF) 946 for (;;) { 947 l = *++cp; 948 l = (l<<8) + *++cp; 949 l = (l<<8) + *++cp; 950 l = (l<<8) + *++cp; 951 if (l == 0) { 952 printf("\t0.0.0.0"); 953 } else { 954 struct in_addr ina; 955 ina.s_addr = ntohl(l); 956 printf("\t%s", pr_addr(ina)); 957 } 958 hlen -= 4; 959 j -= 4; 960 if (j <= IPOPT_MINOFF) 961 break; 962 (void)putchar('\n'); 963 } 964 break; 965 case IPOPT_RR: 966 j = *++cp; /* get length */ 967 i = *++cp; /* and pointer */ 968 hlen -= 2; 969 if (i > j) 970 i = j; 971 i -= IPOPT_MINOFF; 972 if (i <= 0) 973 continue; 974 if (i == old_rrlen 975 && cp == (u_char *)buf + sizeof(struct ip) + 2 976 && !bcmp((char *)cp, old_rr, i) 977 && !(options & F_FLOOD)) { 978 (void)printf("\t(same route)"); 979 i = ((i + 3) / 4) * 4; 980 hlen -= i; 981 cp += i; 982 break; 983 } 984 if (i < MAX_IPOPTLEN) { 985 old_rrlen = i; 986 bcopy((char *)cp, old_rr, i); 987 } else 988 old_rrlen = 0; 989 990 (void)printf("\nRR: "); 991 j = 0; 992 for (;;) { 993 l = *++cp; 994 l = (l<<8) + *++cp; 995 l = (l<<8) + *++cp; 996 l = (l<<8) + *++cp; 997 if (l == 0) { 998 printf("\t0.0.0.0"); 999 } else { 1000 struct in_addr ina; 1001 ina.s_addr = ntohl(l); 1002 printf("\t%s", pr_addr(ina)); 1003 } 1004 hlen -= 4; 1005 i -= 4; 1006 j += 4; 1007 if (i <= 0) 1008 break; 1009 if (j >= MAX_IPOPTLEN) { 1010 (void) printf("\t(truncated route)"); 1011 break; 1012 } 1013 (void)putchar('\n'); 1014 } 1015 break; 1016 case IPOPT_NOP: 1017 (void)printf("\nNOP"); 1018 break; 1019 default: 1020 (void)printf("\nunknown option %x", *cp); 1021 break; 1022 } 1023 if (!(options & F_FLOOD)) { 1024 (void)putchar('\n'); 1025 (void)fflush(stdout); 1026 } 1027 } 1028 1029 /* 1030 * in_cksum -- 1031 * Checksum routine for Internet Protocol family headers (C Version) 1032 */ 1033 u_short 1034 in_cksum(addr, len) 1035 u_short *addr; 1036 int len; 1037 { 1038 register int nleft = len; 1039 register u_short *w = addr; 1040 register int sum = 0; 1041 union { 1042 u_short us; 1043 u_char uc[2]; 1044 } last; 1045 u_short answer; 1046 1047 /* 1048 * Our algorithm is simple, using a 32 bit accumulator (sum), we add 1049 * sequential 16 bit words to it, and at the end, fold back all the 1050 * carry bits from the top 16 bits into the lower 16 bits. 1051 */ 1052 while (nleft > 1) { 1053 sum += *w++; 1054 nleft -= 2; 1055 } 1056 1057 /* mop up an odd byte, if necessary */ 1058 if (nleft == 1) { 1059 last.uc[0] = *(u_char *)w; 1060 last.uc[1] = 0; 1061 sum += last.us; 1062 } 1063 1064 /* add back carry outs from top 16 bits to low 16 bits */ 1065 sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */ 1066 sum += (sum >> 16); /* add carry */ 1067 answer = ~sum; /* truncate to 16 bits */ 1068 return(answer); 1069 } 1070 1071 /* 1072 * tvsub -- 1073 * Subtract 2 timeval structs: out = out - in. Out is assumed to 1074 * be >= in. 1075 */ 1076 static void 1077 tvsub(out, in) 1078 register struct timeval *out, *in; 1079 { 1080 if ((out->tv_usec -= in->tv_usec) < 0) { 1081 --out->tv_sec; 1082 out->tv_usec += 1000000; 1083 } 1084 out->tv_sec -= in->tv_sec; 1085 } 1086 1087 /* 1088 * status -- 1089 * Print out statistics when SIGINFO is received. 1090 */ 1091 1092 static void 1093 status(sig) 1094 int sig; 1095 { 1096 siginfo_p = 1; 1097 } 1098 1099 static void 1100 check_status() 1101 { 1102 if (siginfo_p) { 1103 siginfo_p = 0; 1104 (void)fprintf(stderr, 1105 "\r%ld/%ld packets received (%.0f%%) %.3f min / %.3f avg / %.3f max\n", 1106 nreceived, ntransmitted, 1107 ntransmitted ? nreceived * 100.0 / ntransmitted : 0.0, 1108 nreceived ? tmin : 0.0, 1109 nreceived + nrepeats ? tsum / (nreceived + nrepeats) : tsum, 1110 tmax); 1111 } 1112 } 1113 1114 /* 1115 * finish -- 1116 * Print out statistics, and give up. 1117 */ 1118 static void 1119 finish() 1120 { 1121 struct termios ts; 1122 1123 (void)signal(SIGINT, SIG_IGN); 1124 (void)signal(SIGALRM, SIG_IGN); 1125 (void)putchar('\n'); 1126 (void)fflush(stdout); 1127 (void)printf("--- %s ping statistics ---\n", hostname); 1128 (void)printf("%ld packets transmitted, ", ntransmitted); 1129 (void)printf("%ld packets received, ", nreceived); 1130 if (nrepeats) 1131 (void)printf("+%ld duplicates, ", nrepeats); 1132 if (ntransmitted) { 1133 if (nreceived > ntransmitted) 1134 (void)printf("-- somebody's printing up packets!"); 1135 else 1136 (void)printf("%d%% packet loss", 1137 (int) (((ntransmitted - nreceived) * 100) / 1138 ntransmitted)); 1139 } 1140 (void)putchar('\n'); 1141 if (nreceived && timing) { 1142 double n = nreceived + nrepeats; 1143 double avg = tsum / n; 1144 double vari = tsumsq / n - avg * avg; 1145 printf("round-trip min/avg/max/stddev = " 1146 "%.3f/%.3f/%.3f/%.3f ms\n", 1147 tmin, avg, tmax, sqrt(vari)); 1148 } 1149 if (reset_kerninfo && tcgetattr(STDOUT_FILENO, &ts) != -1) { 1150 ts.c_lflag &= ~NOKERNINFO; 1151 tcsetattr(STDOUT_FILENO, TCSANOW, &ts); 1152 } 1153 1154 if (nreceived) 1155 exit(0); 1156 else 1157 exit(2); 1158 } 1159 1160 #ifdef notdef 1161 static char *ttab[] = { 1162 "Echo Reply", /* ip + seq + udata */ 1163 "Dest Unreachable", /* net, host, proto, port, frag, sr + IP */ 1164 "Source Quench", /* IP */ 1165 "Redirect", /* redirect type, gateway, + IP */ 1166 "Echo", 1167 "Time Exceeded", /* transit, frag reassem + IP */ 1168 "Parameter Problem", /* pointer + IP */ 1169 "Timestamp", /* id + seq + three timestamps */ 1170 "Timestamp Reply", /* " */ 1171 "Info Request", /* id + sq */ 1172 "Info Reply" /* " */ 1173 }; 1174 #endif 1175 1176 /* 1177 * pr_icmph -- 1178 * Print a descriptive string about an ICMP header. 1179 */ 1180 static void 1181 pr_icmph(icp) 1182 struct icmp *icp; 1183 { 1184 switch(icp->icmp_type) { 1185 case ICMP_ECHOREPLY: 1186 (void)printf("Echo Reply\n"); 1187 /* XXX ID + Seq + Data */ 1188 break; 1189 case ICMP_UNREACH: 1190 switch(icp->icmp_code) { 1191 case ICMP_UNREACH_NET: 1192 (void)printf("Destination Net Unreachable\n"); 1193 break; 1194 case ICMP_UNREACH_HOST: 1195 (void)printf("Destination Host Unreachable\n"); 1196 break; 1197 case ICMP_UNREACH_PROTOCOL: 1198 (void)printf("Destination Protocol Unreachable\n"); 1199 break; 1200 case ICMP_UNREACH_PORT: 1201 (void)printf("Destination Port Unreachable\n"); 1202 break; 1203 case ICMP_UNREACH_NEEDFRAG: 1204 (void)printf("frag needed and DF set (MTU %d)\n", 1205 ntohs(icp->icmp_nextmtu)); 1206 break; 1207 case ICMP_UNREACH_SRCFAIL: 1208 (void)printf("Source Route Failed\n"); 1209 break; 1210 case ICMP_UNREACH_FILTER_PROHIB: 1211 (void)printf("Communication prohibited by filter\n"); 1212 break; 1213 default: 1214 (void)printf("Dest Unreachable, Bad Code: %d\n", 1215 icp->icmp_code); 1216 break; 1217 } 1218 /* Print returned IP header information */ 1219 #ifndef icmp_data 1220 pr_retip(&icp->icmp_ip); 1221 #else 1222 pr_retip((struct ip *)icp->icmp_data); 1223 #endif 1224 break; 1225 case ICMP_SOURCEQUENCH: 1226 (void)printf("Source Quench\n"); 1227 #ifndef icmp_data 1228 pr_retip(&icp->icmp_ip); 1229 #else 1230 pr_retip((struct ip *)icp->icmp_data); 1231 #endif 1232 break; 1233 case ICMP_REDIRECT: 1234 switch(icp->icmp_code) { 1235 case ICMP_REDIRECT_NET: 1236 (void)printf("Redirect Network"); 1237 break; 1238 case ICMP_REDIRECT_HOST: 1239 (void)printf("Redirect Host"); 1240 break; 1241 case ICMP_REDIRECT_TOSNET: 1242 (void)printf("Redirect Type of Service and Network"); 1243 break; 1244 case ICMP_REDIRECT_TOSHOST: 1245 (void)printf("Redirect Type of Service and Host"); 1246 break; 1247 default: 1248 (void)printf("Redirect, Bad Code: %d", icp->icmp_code); 1249 break; 1250 } 1251 (void)printf("(New addr: %s)\n", inet_ntoa(icp->icmp_gwaddr)); 1252 #ifndef icmp_data 1253 pr_retip(&icp->icmp_ip); 1254 #else 1255 pr_retip((struct ip *)icp->icmp_data); 1256 #endif 1257 break; 1258 case ICMP_ECHO: 1259 (void)printf("Echo Request\n"); 1260 /* XXX ID + Seq + Data */ 1261 break; 1262 case ICMP_TIMXCEED: 1263 switch(icp->icmp_code) { 1264 case ICMP_TIMXCEED_INTRANS: 1265 (void)printf("Time to live exceeded\n"); 1266 break; 1267 case ICMP_TIMXCEED_REASS: 1268 (void)printf("Frag reassembly time exceeded\n"); 1269 break; 1270 default: 1271 (void)printf("Time exceeded, Bad Code: %d\n", 1272 icp->icmp_code); 1273 break; 1274 } 1275 #ifndef icmp_data 1276 pr_retip(&icp->icmp_ip); 1277 #else 1278 pr_retip((struct ip *)icp->icmp_data); 1279 #endif 1280 break; 1281 case ICMP_PARAMPROB: 1282 (void)printf("Parameter problem: pointer = 0x%02x\n", 1283 icp->icmp_hun.ih_pptr); 1284 #ifndef icmp_data 1285 pr_retip(&icp->icmp_ip); 1286 #else 1287 pr_retip((struct ip *)icp->icmp_data); 1288 #endif 1289 break; 1290 case ICMP_TSTAMP: 1291 (void)printf("Timestamp\n"); 1292 /* XXX ID + Seq + 3 timestamps */ 1293 break; 1294 case ICMP_TSTAMPREPLY: 1295 (void)printf("Timestamp Reply\n"); 1296 /* XXX ID + Seq + 3 timestamps */ 1297 break; 1298 case ICMP_IREQ: 1299 (void)printf("Information Request\n"); 1300 /* XXX ID + Seq */ 1301 break; 1302 case ICMP_IREQREPLY: 1303 (void)printf("Information Reply\n"); 1304 /* XXX ID + Seq */ 1305 break; 1306 case ICMP_MASKREQ: 1307 (void)printf("Address Mask Request\n"); 1308 break; 1309 case ICMP_MASKREPLY: 1310 (void)printf("Address Mask Reply\n"); 1311 break; 1312 case ICMP_ROUTERADVERT: 1313 (void)printf("Router Advertisement\n"); 1314 break; 1315 case ICMP_ROUTERSOLICIT: 1316 (void)printf("Router Solicitation\n"); 1317 break; 1318 default: 1319 (void)printf("Bad ICMP type: %d\n", icp->icmp_type); 1320 } 1321 } 1322 1323 /* 1324 * pr_iph -- 1325 * Print an IP header with options. 1326 */ 1327 static void 1328 pr_iph(ip) 1329 struct ip *ip; 1330 { 1331 int hlen; 1332 u_char *cp; 1333 1334 hlen = ip->ip_hl << 2; 1335 cp = (u_char *)ip + 20; /* point to options */ 1336 1337 (void)printf("Vr HL TOS Len ID Flg off TTL Pro cks Src Dst\n"); 1338 (void)printf(" %1x %1x %02x %04x %04x", 1339 ip->ip_v, ip->ip_hl, ip->ip_tos, ntohs(ip->ip_len), 1340 ntohs(ip->ip_id)); 1341 (void)printf(" %1lx %04lx", 1342 (u_long) (ntohl(ip->ip_off) & 0xe000) >> 13, 1343 (u_long) ntohl(ip->ip_off) & 0x1fff); 1344 (void)printf(" %02x %02x %04x", ip->ip_ttl, ip->ip_p, 1345 ntohs(ip->ip_sum)); 1346 (void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_src.s_addr)); 1347 (void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_dst.s_addr)); 1348 /* dump any option bytes */ 1349 while (hlen-- > 20) { 1350 (void)printf("%02x", *cp++); 1351 } 1352 (void)putchar('\n'); 1353 } 1354 1355 /* 1356 * pr_addr -- 1357 * Return an ascii host address as a dotted quad and optionally with 1358 * a hostname. 1359 */ 1360 static char * 1361 pr_addr(ina) 1362 struct in_addr ina; 1363 { 1364 struct hostent *hp; 1365 static char buf[16 + 3 + MAXHOSTNAMELEN]; 1366 1367 if ((options & F_NUMERIC) || 1368 !(hp = gethostbyaddr((char *)&ina, 4, AF_INET))) 1369 return inet_ntoa(ina); 1370 else 1371 (void)snprintf(buf, sizeof(buf), "%s (%s)", hp->h_name, 1372 inet_ntoa(ina)); 1373 return(buf); 1374 } 1375 1376 /* 1377 * pr_retip -- 1378 * Dump some info on a returned (via ICMP) IP packet. 1379 */ 1380 static void 1381 pr_retip(ip) 1382 struct ip *ip; 1383 { 1384 int hlen; 1385 u_char *cp; 1386 1387 pr_iph(ip); 1388 hlen = ip->ip_hl << 2; 1389 cp = (u_char *)ip + hlen; 1390 1391 if (ip->ip_p == 6) 1392 (void)printf("TCP: from port %u, to port %u (decimal)\n", 1393 (*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3))); 1394 else if (ip->ip_p == 17) 1395 (void)printf("UDP: from port %u, to port %u (decimal)\n", 1396 (*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3))); 1397 } 1398 1399 static void 1400 fill(bp, patp) 1401 char *bp, *patp; 1402 { 1403 register int ii, jj, kk; 1404 int pat[16]; 1405 char *cp; 1406 1407 for (cp = patp; *cp; cp++) { 1408 if (!isxdigit(*cp)) 1409 errx(EX_USAGE, 1410 "patterns must be specified as hex digits"); 1411 1412 } 1413 ii = sscanf(patp, 1414 "%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x", 1415 &pat[0], &pat[1], &pat[2], &pat[3], &pat[4], &pat[5], &pat[6], 1416 &pat[7], &pat[8], &pat[9], &pat[10], &pat[11], &pat[12], 1417 &pat[13], &pat[14], &pat[15]); 1418 1419 if (ii > 0) 1420 for (kk = 0; 1421 kk <= MAXPACKET - (8 + PHDR_LEN + ii); 1422 kk += ii) 1423 for (jj = 0; jj < ii; ++jj) 1424 bp[jj + kk] = pat[jj]; 1425 if (!(options & F_QUIET)) { 1426 (void)printf("PATTERN: 0x"); 1427 for (jj = 0; jj < ii; ++jj) 1428 (void)printf("%02x", bp[jj] & 0xFF); 1429 (void)printf("\n"); 1430 } 1431 } 1432 1433 static void 1434 usage() 1435 { 1436 fprintf(stderr, "%s\n%s\n%s\n", 1437 "usage: ping [-QRadfnqrv] [-c count] [-i wait] [-l preload] [-m ttl]", 1438 " [-p pattern] " 1439 #ifdef IPSEC 1440 #ifdef IPSEC_POLICY_IPSEC 1441 "[-P policy] " 1442 #endif 1443 #endif 1444 "[-s packetsize] [-S src_addr] [-t timeout]", 1445 " [host | [-L] [-I iface] [-T ttl] mcast-group]"); 1446 exit(EX_USAGE); 1447 } 1448