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