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