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