ping.c revision 92806
1/* 2 * Copyright (c) 1989, 1993 3 * The Regents of the University of California. All rights reserved. 4 * 5 * This code is derived from software contributed to Berkeley by 6 * Mike Muuss. 7 * 8 * Redistribution and use in source and binary forms, with or without 9 * modification, are permitted provided that the following conditions 10 * are met: 11 * 1. Redistributions of source code must retain the above copyright 12 * notice, this list of conditions and the following disclaimer. 13 * 2. Redistributions in binary form must reproduce the above copyright 14 * notice, this list of conditions and the following disclaimer in the 15 * documentation and/or other materials provided with the distribution. 16 * 3. All advertising materials mentioning features or use of this software 17 * must display the following acknowledgement: 18 * This product includes software developed by the University of 19 * California, Berkeley and its contributors. 20 * 4. Neither the name of the University nor the names of its contributors 21 * may be used to endorse or promote products derived from this software 22 * without specific prior written permission. 23 * 24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 34 * SUCH DAMAGE. 35 */ 36 37#ifndef lint 38static const char copyright[] = 39"@(#) Copyright (c) 1989, 1993\n\ 40 The Regents of the University of California. All rights reserved.\n"; 41#endif /* not lint */ 42 43#ifndef lint 44#if 0 45static char sccsid[] = "@(#)ping.c 8.1 (Berkeley) 6/5/93"; 46#endif 47static const char rcsid[] = 48 "$FreeBSD: head/sbin/ping/ping.c 92806 2002-03-20 17:55:10Z obrien $"; 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 */ 117int 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) 146int mx_dup_ck = MAX_DUP_CHK; 147char rcvd_tbl[MAX_DUP_CHK / 8]; 148 149struct sockaddr_in whereto; /* who to ping */ 150int datalen = DEFDATALEN; 151int s; /* socket file descriptor */ 152u_char outpack[MAXPACKET]; 153char BSPACE = '\b'; /* characters written for flood */ 154char BBELL = '\a'; /* characters written for MISSED and AUDIBLE */ 155char DOT = '.'; 156char *hostname; 157char *shostname; 158int ident; /* process id to identify our packets */ 159int uid; /* cached uid for micro-optimization */ 160 161/* counters */ 162long npackets; /* max packets to transmit */ 163long nreceived; /* # of packets we got back */ 164long nrepeats; /* number of duplicates */ 165long ntransmitted; /* sequence # for outbound packets = #sent */ 166long nmissedmax; /* max value of ntransmitted - nreceived - 1 */ 167int interval = 1000; /* interval between packets, ms */ 168 169/* timing */ 170int timing; /* flag to do timing */ 171double tmin = 999999999.0; /* minimum round trip time */ 172double tmax = 0.0; /* maximum round trip time */ 173double tsum = 0.0; /* sum of all times, for doing average */ 174double tsumsq = 0.0; /* sum of all times squared, for std. dev. */ 175 176volatile sig_atomic_t finish_up; /* nonzero if we've been told to finish up */ 177int reset_kerninfo; 178volatile sig_atomic_t siginfo_p; 179 180static void fill(char *, char *); 181static u_short in_cksum(u_short *, int); 182static void check_status(void); 183static void finish(void) __dead2; 184static void pinger(void); 185static char *pr_addr(struct in_addr); 186static void pr_icmph(struct icmp *); 187static void pr_iph(struct ip *); 188static void pr_pack(char *, int, struct sockaddr_in *, struct timeval *); 189static void pr_retip(struct ip *); 190static void status(int); 191static void stopit(int); 192static void tvsub(struct timeval *, struct timeval *); 193static void usage(void) __dead2; 194 195int 196main(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 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 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 */ 732void 733stopit(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 */ 747static void 748pinger(void) 749{ 750 struct icmp *icp; 751 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 = htons(ntransmitted); 759 icp->icmp_id = ident; /* ID */ 760 761 CLR(ntransmitted % 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 */ 799static void 800pr_pack(buf, cc, from, tv) 801 char *buf; 802 int cc; 803 struct sockaddr_in *from; 804 struct timeval *tv; 805{ 806 struct icmp *icp; 807 u_long l; 808 int i, j; 809 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, seq; 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 */ 1039u_short 1040in_cksum(addr, len) 1041 u_short *addr; 1042 int len; 1043{ 1044 int nleft = len; 1045 u_short *w = addr; 1046 int sum = 0; 1047 union { 1048 u_short us; 1049 u_char uc[2]; 1050 } last; 1051 u_short answer; 1052 1053 /* 1054 * Our algorithm is simple, using a 32 bit accumulator (sum), we add 1055 * sequential 16 bit words to it, and at the end, fold back all the 1056 * carry bits from the top 16 bits into the lower 16 bits. 1057 */ 1058 while (nleft > 1) { 1059 sum += *w++; 1060 nleft -= 2; 1061 } 1062 1063 /* mop up an odd byte, if necessary */ 1064 if (nleft == 1) { 1065 last.uc[0] = *(u_char *)w; 1066 last.uc[1] = 0; 1067 sum += last.us; 1068 } 1069 1070 /* add back carry outs from top 16 bits to low 16 bits */ 1071 sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */ 1072 sum += (sum >> 16); /* add carry */ 1073 answer = ~sum; /* truncate to 16 bits */ 1074 return(answer); 1075} 1076 1077/* 1078 * tvsub -- 1079 * Subtract 2 timeval structs: out = out - in. Out is assumed to 1080 * be >= in. 1081 */ 1082static void 1083tvsub(out, in) 1084 struct timeval *out, *in; 1085{ 1086 if ((out->tv_usec -= in->tv_usec) < 0) { 1087 --out->tv_sec; 1088 out->tv_usec += 1000000; 1089 } 1090 out->tv_sec -= in->tv_sec; 1091} 1092 1093/* 1094 * status -- 1095 * Print out statistics when SIGINFO is received. 1096 */ 1097 1098static void 1099status(sig) 1100 int sig; 1101{ 1102 siginfo_p = 1; 1103} 1104 1105static void 1106check_status() 1107{ 1108 if (siginfo_p) { 1109 siginfo_p = 0; 1110 (void)fprintf(stderr, 1111 "\r%ld/%ld packets received (%.0f%%) %.3f min / %.3f avg / %.3f max\n", 1112 nreceived, ntransmitted, 1113 ntransmitted ? nreceived * 100.0 / ntransmitted : 0.0, 1114 nreceived ? tmin : 0.0, 1115 nreceived + nrepeats ? tsum / (nreceived + nrepeats) : tsum, 1116 tmax); 1117 } 1118} 1119 1120/* 1121 * finish -- 1122 * Print out statistics, and give up. 1123 */ 1124static void 1125finish() 1126{ 1127 struct termios ts; 1128 1129 (void)signal(SIGINT, SIG_IGN); 1130 (void)signal(SIGALRM, SIG_IGN); 1131 (void)putchar('\n'); 1132 (void)fflush(stdout); 1133 (void)printf("--- %s ping statistics ---\n", hostname); 1134 (void)printf("%ld packets transmitted, ", ntransmitted); 1135 (void)printf("%ld packets received, ", nreceived); 1136 if (nrepeats) 1137 (void)printf("+%ld duplicates, ", nrepeats); 1138 if (ntransmitted) { 1139 if (nreceived > ntransmitted) 1140 (void)printf("-- somebody's printing up packets!"); 1141 else 1142 (void)printf("%d%% packet loss", 1143 (int) (((ntransmitted - nreceived) * 100) / 1144 ntransmitted)); 1145 } 1146 (void)putchar('\n'); 1147 if (nreceived && timing) { 1148 double n = nreceived + nrepeats; 1149 double avg = tsum / n; 1150 double vari = tsumsq / n - avg * avg; 1151 printf("round-trip min/avg/max/stddev = " 1152 "%.3f/%.3f/%.3f/%.3f ms\n", 1153 tmin, avg, tmax, sqrt(vari)); 1154 } 1155 if (reset_kerninfo && tcgetattr(STDOUT_FILENO, &ts) != -1) { 1156 ts.c_lflag &= ~NOKERNINFO; 1157 tcsetattr(STDOUT_FILENO, TCSANOW, &ts); 1158 } 1159 1160 if (nreceived) 1161 exit(0); 1162 else 1163 exit(2); 1164} 1165 1166#ifdef notdef 1167static char *ttab[] = { 1168 "Echo Reply", /* ip + seq + udata */ 1169 "Dest Unreachable", /* net, host, proto, port, frag, sr + IP */ 1170 "Source Quench", /* IP */ 1171 "Redirect", /* redirect type, gateway, + IP */ 1172 "Echo", 1173 "Time Exceeded", /* transit, frag reassem + IP */ 1174 "Parameter Problem", /* pointer + IP */ 1175 "Timestamp", /* id + seq + three timestamps */ 1176 "Timestamp Reply", /* " */ 1177 "Info Request", /* id + sq */ 1178 "Info Reply" /* " */ 1179}; 1180#endif 1181 1182/* 1183 * pr_icmph -- 1184 * Print a descriptive string about an ICMP header. 1185 */ 1186static void 1187pr_icmph(icp) 1188 struct icmp *icp; 1189{ 1190 switch(icp->icmp_type) { 1191 case ICMP_ECHOREPLY: 1192 (void)printf("Echo Reply\n"); 1193 /* XXX ID + Seq + Data */ 1194 break; 1195 case ICMP_UNREACH: 1196 switch(icp->icmp_code) { 1197 case ICMP_UNREACH_NET: 1198 (void)printf("Destination Net Unreachable\n"); 1199 break; 1200 case ICMP_UNREACH_HOST: 1201 (void)printf("Destination Host Unreachable\n"); 1202 break; 1203 case ICMP_UNREACH_PROTOCOL: 1204 (void)printf("Destination Protocol Unreachable\n"); 1205 break; 1206 case ICMP_UNREACH_PORT: 1207 (void)printf("Destination Port Unreachable\n"); 1208 break; 1209 case ICMP_UNREACH_NEEDFRAG: 1210 (void)printf("frag needed and DF set (MTU %d)\n", 1211 ntohs(icp->icmp_nextmtu)); 1212 break; 1213 case ICMP_UNREACH_SRCFAIL: 1214 (void)printf("Source Route Failed\n"); 1215 break; 1216 case ICMP_UNREACH_FILTER_PROHIB: 1217 (void)printf("Communication prohibited by filter\n"); 1218 break; 1219 default: 1220 (void)printf("Dest Unreachable, Bad Code: %d\n", 1221 icp->icmp_code); 1222 break; 1223 } 1224 /* Print returned IP header information */ 1225#ifndef icmp_data 1226 pr_retip(&icp->icmp_ip); 1227#else 1228 pr_retip((struct ip *)icp->icmp_data); 1229#endif 1230 break; 1231 case ICMP_SOURCEQUENCH: 1232 (void)printf("Source Quench\n"); 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_REDIRECT: 1240 switch(icp->icmp_code) { 1241 case ICMP_REDIRECT_NET: 1242 (void)printf("Redirect Network"); 1243 break; 1244 case ICMP_REDIRECT_HOST: 1245 (void)printf("Redirect Host"); 1246 break; 1247 case ICMP_REDIRECT_TOSNET: 1248 (void)printf("Redirect Type of Service and Network"); 1249 break; 1250 case ICMP_REDIRECT_TOSHOST: 1251 (void)printf("Redirect Type of Service and Host"); 1252 break; 1253 default: 1254 (void)printf("Redirect, Bad Code: %d", icp->icmp_code); 1255 break; 1256 } 1257 (void)printf("(New addr: %s)\n", inet_ntoa(icp->icmp_gwaddr)); 1258#ifndef icmp_data 1259 pr_retip(&icp->icmp_ip); 1260#else 1261 pr_retip((struct ip *)icp->icmp_data); 1262#endif 1263 break; 1264 case ICMP_ECHO: 1265 (void)printf("Echo Request\n"); 1266 /* XXX ID + Seq + Data */ 1267 break; 1268 case ICMP_TIMXCEED: 1269 switch(icp->icmp_code) { 1270 case ICMP_TIMXCEED_INTRANS: 1271 (void)printf("Time to live exceeded\n"); 1272 break; 1273 case ICMP_TIMXCEED_REASS: 1274 (void)printf("Frag reassembly time exceeded\n"); 1275 break; 1276 default: 1277 (void)printf("Time exceeded, Bad Code: %d\n", 1278 icp->icmp_code); 1279 break; 1280 } 1281#ifndef icmp_data 1282 pr_retip(&icp->icmp_ip); 1283#else 1284 pr_retip((struct ip *)icp->icmp_data); 1285#endif 1286 break; 1287 case ICMP_PARAMPROB: 1288 (void)printf("Parameter problem: pointer = 0x%02x\n", 1289 icp->icmp_hun.ih_pptr); 1290#ifndef icmp_data 1291 pr_retip(&icp->icmp_ip); 1292#else 1293 pr_retip((struct ip *)icp->icmp_data); 1294#endif 1295 break; 1296 case ICMP_TSTAMP: 1297 (void)printf("Timestamp\n"); 1298 /* XXX ID + Seq + 3 timestamps */ 1299 break; 1300 case ICMP_TSTAMPREPLY: 1301 (void)printf("Timestamp Reply\n"); 1302 /* XXX ID + Seq + 3 timestamps */ 1303 break; 1304 case ICMP_IREQ: 1305 (void)printf("Information Request\n"); 1306 /* XXX ID + Seq */ 1307 break; 1308 case ICMP_IREQREPLY: 1309 (void)printf("Information Reply\n"); 1310 /* XXX ID + Seq */ 1311 break; 1312 case ICMP_MASKREQ: 1313 (void)printf("Address Mask Request\n"); 1314 break; 1315 case ICMP_MASKREPLY: 1316 (void)printf("Address Mask Reply\n"); 1317 break; 1318 case ICMP_ROUTERADVERT: 1319 (void)printf("Router Advertisement\n"); 1320 break; 1321 case ICMP_ROUTERSOLICIT: 1322 (void)printf("Router Solicitation\n"); 1323 break; 1324 default: 1325 (void)printf("Bad ICMP type: %d\n", icp->icmp_type); 1326 } 1327} 1328 1329/* 1330 * pr_iph -- 1331 * Print an IP header with options. 1332 */ 1333static void 1334pr_iph(ip) 1335 struct ip *ip; 1336{ 1337 int hlen; 1338 u_char *cp; 1339 1340 hlen = ip->ip_hl << 2; 1341 cp = (u_char *)ip + 20; /* point to options */ 1342 1343 (void)printf("Vr HL TOS Len ID Flg off TTL Pro cks Src Dst\n"); 1344 (void)printf(" %1x %1x %02x %04x %04x", 1345 ip->ip_v, ip->ip_hl, ip->ip_tos, ntohs(ip->ip_len), 1346 ntohs(ip->ip_id)); 1347 (void)printf(" %1lx %04lx", 1348 (u_long) (ntohl(ip->ip_off) & 0xe000) >> 13, 1349 (u_long) ntohl(ip->ip_off) & 0x1fff); 1350 (void)printf(" %02x %02x %04x", ip->ip_ttl, ip->ip_p, 1351 ntohs(ip->ip_sum)); 1352 (void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_src.s_addr)); 1353 (void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_dst.s_addr)); 1354 /* dump any option bytes */ 1355 while (hlen-- > 20) { 1356 (void)printf("%02x", *cp++); 1357 } 1358 (void)putchar('\n'); 1359} 1360 1361/* 1362 * pr_addr -- 1363 * Return an ascii host address as a dotted quad and optionally with 1364 * a hostname. 1365 */ 1366static char * 1367pr_addr(ina) 1368 struct in_addr ina; 1369{ 1370 struct hostent *hp; 1371 static char buf[16 + 3 + MAXHOSTNAMELEN]; 1372 1373 if ((options & F_NUMERIC) || 1374 !(hp = gethostbyaddr((char *)&ina, 4, AF_INET))) 1375 return inet_ntoa(ina); 1376 else 1377 (void)snprintf(buf, sizeof(buf), "%s (%s)", hp->h_name, 1378 inet_ntoa(ina)); 1379 return(buf); 1380} 1381 1382/* 1383 * pr_retip -- 1384 * Dump some info on a returned (via ICMP) IP packet. 1385 */ 1386static void 1387pr_retip(ip) 1388 struct ip *ip; 1389{ 1390 int hlen; 1391 u_char *cp; 1392 1393 pr_iph(ip); 1394 hlen = ip->ip_hl << 2; 1395 cp = (u_char *)ip + hlen; 1396 1397 if (ip->ip_p == 6) 1398 (void)printf("TCP: from port %u, to port %u (decimal)\n", 1399 (*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3))); 1400 else if (ip->ip_p == 17) 1401 (void)printf("UDP: from port %u, to port %u (decimal)\n", 1402 (*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3))); 1403} 1404 1405static void 1406fill(bp, patp) 1407 char *bp, *patp; 1408{ 1409 int ii, jj, kk; 1410 int pat[16]; 1411 char *cp; 1412 1413 for (cp = patp; *cp; cp++) { 1414 if (!isxdigit(*cp)) 1415 errx(EX_USAGE, 1416 "patterns must be specified as hex digits"); 1417 1418 } 1419 ii = sscanf(patp, 1420 "%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x", 1421 &pat[0], &pat[1], &pat[2], &pat[3], &pat[4], &pat[5], &pat[6], 1422 &pat[7], &pat[8], &pat[9], &pat[10], &pat[11], &pat[12], 1423 &pat[13], &pat[14], &pat[15]); 1424 1425 if (ii > 0) 1426 for (kk = 0; 1427 kk <= MAXPACKET - (8 + PHDR_LEN + ii); 1428 kk += ii) 1429 for (jj = 0; jj < ii; ++jj) 1430 bp[jj + kk] = pat[jj]; 1431 if (!(options & F_QUIET)) { 1432 (void)printf("PATTERN: 0x"); 1433 for (jj = 0; jj < ii; ++jj) 1434 (void)printf("%02x", bp[jj] & 0xFF); 1435 (void)printf("\n"); 1436 } 1437} 1438 1439static void 1440usage() 1441{ 1442 fprintf(stderr, "%s\n%s\n%s\n", 1443"usage: ping [-QRadfnqrv] [-c count] [-i wait] [-l preload] [-m ttl]", 1444" [-p pattern] " 1445#ifdef IPSEC 1446#ifdef IPSEC_POLICY_IPSEC 1447"[-P policy] " 1448#endif 1449#endif 1450"[-s packetsize] [-S src_addr] [-t timeout]", 1451" [host | [-L] [-I iface] [-T ttl] mcast-group]"); 1452 exit(EX_USAGE); 1453} 1454