1 /* 2 * Copyright (c) 1995, 2019, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package java.net; 27 28 import java.util.NavigableSet; 29 import java.util.ArrayList; 30 import java.util.Objects; 31 import java.util.Scanner; 32 import java.security.AccessController; 33 import java.io.File; 34 import java.io.FileNotFoundException; 35 import java.io.ObjectStreamException; 36 import java.io.ObjectStreamField; 37 import java.io.IOException; 38 import java.io.InvalidObjectException; 39 import java.io.ObjectInputStream; 40 import java.io.ObjectInputStream.GetField; 41 import java.io.ObjectOutputStream; 42 import java.io.ObjectOutputStream.PutField; 43 import java.lang.annotation.Native; 44 import java.util.concurrent.ConcurrentHashMap; 45 import java.util.concurrent.ConcurrentMap; 46 import java.util.concurrent.ConcurrentSkipListSet; 47 import java.util.concurrent.atomic.AtomicLong; 48 import java.util.Arrays; 49 50 import jdk.internal.access.JavaNetInetAddressAccess; 51 import jdk.internal.access.SharedSecrets; 52 import sun.security.action.*; 53 import sun.net.InetAddressCachePolicy; 54 import sun.net.util.IPAddressUtil; 55 56 /** 57 * This class represents an Internet Protocol (IP) address. 58 * 59 * <p> An IP address is either a 32-bit or 128-bit unsigned number 60 * used by IP, a lower-level protocol on which protocols like UDP and 61 * TCP are built. The IP address architecture is defined by <a 62 * href="http://www.ietf.org/rfc/rfc790.txt"><i>RFC 790: 63 * Assigned Numbers</i></a>, <a 64 * href="http://www.ietf.org/rfc/rfc1918.txt"> <i>RFC 1918: 65 * Address Allocation for Private Internets</i></a>, <a 66 * href="http://www.ietf.org/rfc/rfc2365.txt"><i>RFC 2365: 67 * Administratively Scoped IP Multicast</i></a>, and <a 68 * href="http://www.ietf.org/rfc/rfc2373.txt"><i>RFC 2373: IP 69 * Version 6 Addressing Architecture</i></a>. An instance of an 70 * InetAddress consists of an IP address and possibly its 71 * corresponding host name (depending on whether it is constructed 72 * with a host name or whether it has already done reverse host name 73 * resolution). 74 * 75 * <h2> Address types </h2> 76 * 77 * <table class="striped" style="margin-left:2em"> 78 * <caption style="display:none">Description of unicast and multicast address types</caption> 79 * <thead> 80 * <tr><th scope="col">Address Type</th><th scope="col">Description</th></tr> 81 * </thead> 82 * <tbody> 83 * <tr><th scope="row" style="vertical-align:top">unicast</th> 84 * <td>An identifier for a single interface. A packet sent to 85 * a unicast address is delivered to the interface identified by 86 * that address. 87 * 88 * <p> The Unspecified Address -- Also called anylocal or wildcard 89 * address. It must never be assigned to any node. It indicates the 90 * absence of an address. One example of its use is as the target of 91 * bind, which allows a server to accept a client connection on any 92 * interface, in case the server host has multiple interfaces. 93 * 94 * <p> The <i>unspecified</i> address must not be used as 95 * the destination address of an IP packet. 96 * 97 * <p> The <i>Loopback</i> Addresses -- This is the address 98 * assigned to the loopback interface. Anything sent to this 99 * IP address loops around and becomes IP input on the local 100 * host. This address is often used when testing a 101 * client.</td></tr> 102 * <tr><th scope="row" style="vertical-align:top">multicast</th> 103 * <td>An identifier for a set of interfaces (typically belonging 104 * to different nodes). A packet sent to a multicast address is 105 * delivered to all interfaces identified by that address.</td></tr> 106 * </tbody> 107 * </table> 108 * 109 * <h3> IP address scope </h3> 110 * 111 * <p> <i>Link-local</i> addresses are designed to be used for addressing 112 * on a single link for purposes such as auto-address configuration, 113 * neighbor discovery, or when no routers are present. 114 * 115 * <p> <i>Site-local</i> addresses are designed to be used for addressing 116 * inside of a site without the need for a global prefix. 117 * 118 * <p> <i>Global</i> addresses are unique across the internet. 119 * 120 * <h3> Textual representation of IP addresses </h3> 121 * 122 * The textual representation of an IP address is address family specific. 123 * 124 * <p> 125 * 126 * For IPv4 address format, please refer to <A 127 * HREF="Inet4Address.html#format">Inet4Address#format</A>; For IPv6 128 * address format, please refer to <A 129 * HREF="Inet6Address.html#format">Inet6Address#format</A>. 130 * 131 * <P>There is a <a href="doc-files/net-properties.html#Ipv4IPv6">couple of 132 * System Properties</a> affecting how IPv4 and IPv6 addresses are used.</P> 133 * 134 * <h3> Host Name Resolution </h3> 135 * 136 * Host name-to-IP address <i>resolution</i> is accomplished through 137 * the use of a combination of local machine configuration information 138 * and network naming services such as the Domain Name System (DNS) 139 * and Network Information Service(NIS). The particular naming 140 * services(s) being used is by default the local machine configured 141 * one. For any host name, its corresponding IP address is returned. 142 * 143 * <p> <i>Reverse name resolution</i> means that for any IP address, 144 * the host associated with the IP address is returned. 145 * 146 * <p> The InetAddress class provides methods to resolve host names to 147 * their IP addresses and vice versa. 148 * 149 * <h3> InetAddress Caching </h3> 150 * 151 * The InetAddress class has a cache to store successful as well as 152 * unsuccessful host name resolutions. 153 * 154 * <p> By default, when a security manager is installed, in order to 155 * protect against DNS spoofing attacks, 156 * the result of positive host name resolutions are 157 * cached forever. When a security manager is not installed, the default 158 * behavior is to cache entries for a finite (implementation dependent) 159 * period of time. The result of unsuccessful host 160 * name resolution is cached for a very short period of time (10 161 * seconds) to improve performance. 162 * 163 * <p> If the default behavior is not desired, then a Java security property 164 * can be set to a different Time-to-live (TTL) value for positive 165 * caching. Likewise, a system admin can configure a different 166 * negative caching TTL value when needed. 167 * 168 * <p> Two Java security properties control the TTL values used for 169 * positive and negative host name resolution caching: 170 * 171 * <dl style="margin-left:2em"> 172 * <dt><b>networkaddress.cache.ttl</b></dt> 173 * <dd>Indicates the caching policy for successful name lookups from 174 * the name service. The value is specified as an integer to indicate 175 * the number of seconds to cache the successful lookup. The default 176 * setting is to cache for an implementation specific period of time. 177 * <p> 178 * A value of -1 indicates "cache forever". 179 * </dd> 180 * <dt><b>networkaddress.cache.negative.ttl</b> (default: 10)</dt> 181 * <dd>Indicates the caching policy for un-successful name lookups 182 * from the name service. The value is specified as an integer to 183 * indicate the number of seconds to cache the failure for 184 * un-successful lookups. 185 * <p> 186 * A value of 0 indicates "never cache". 187 * A value of -1 indicates "cache forever". 188 * </dd> 189 * </dl> 190 * 191 * @author Chris Warth 192 * @see java.net.InetAddress#getByAddress(byte[]) 193 * @see java.net.InetAddress#getByAddress(java.lang.String, byte[]) 194 * @see java.net.InetAddress#getAllByName(java.lang.String) 195 * @see java.net.InetAddress#getByName(java.lang.String) 196 * @see java.net.InetAddress#getLocalHost() 197 * @since 1.0 198 */ 199 public 200 class InetAddress implements java.io.Serializable { 201 202 @Native static final int PREFER_IPV4_VALUE = 0; 203 @Native static final int PREFER_IPV6_VALUE = 1; 204 @Native static final int PREFER_SYSTEM_VALUE = 2; 205 206 /** 207 * Specify the address family: Internet Protocol, Version 4 208 * @since 1.4 209 */ 210 @Native static final int IPv4 = 1; 211 212 /** 213 * Specify the address family: Internet Protocol, Version 6 214 * @since 1.4 215 */ 216 @Native static final int IPv6 = 2; 217 218 /* Specify address family preference */ 219 static transient final int preferIPv6Address; 220 221 static class InetAddressHolder { 222 /** 223 * Reserve the original application specified hostname. 224 * 225 * The original hostname is useful for domain-based endpoint 226 * identification (see RFC 2818 and RFC 6125). If an address 227 * was created with a raw IP address, a reverse name lookup 228 * may introduce endpoint identification security issue via 229 * DNS forging. 230 * 231 * Oracle JSSE provider is using this original hostname, via 232 * jdk.internal.misc.JavaNetAccess, for SSL/TLS endpoint identification. 233 * 234 * Note: May define a new public method in the future if necessary. 235 */ 236 String originalHostName; 237 238 InetAddressHolder() {} 239 240 InetAddressHolder(String hostName, int address, int family) { 241 this.originalHostName = hostName; 242 this.hostName = hostName; 243 this.address = address; 244 this.family = family; 245 } 246 247 void init(String hostName, int family) { 248 this.originalHostName = hostName; 249 this.hostName = hostName; 250 if (family != -1) { 251 this.family = family; 252 } 253 } 254 255 String hostName; 256 257 String getHostName() { 258 return hostName; 259 } 260 261 String getOriginalHostName() { 262 return originalHostName; 263 } 264 265 /** 266 * Holds a 32-bit IPv4 address. 267 */ 268 int address; 269 270 int getAddress() { 271 return address; 272 } 273 274 /** 275 * Specifies the address family type, for instance, '1' for IPv4 276 * addresses, and '2' for IPv6 addresses. 277 */ 278 int family; 279 280 int getFamily() { 281 return family; 282 } 283 } 284 285 /* Used to store the serializable fields of InetAddress */ 286 final transient InetAddressHolder holder; 287 288 InetAddressHolder holder() { 289 return holder; 290 } 291 292 /* Used to store the name service provider */ 293 private static transient NameService nameService; 294 295 /** 296 * Used to store the best available hostname. 297 * Lazily initialized via a data race; safe because Strings are immutable. 298 */ 299 private transient String canonicalHostName = null; 300 301 /** use serialVersionUID from JDK 1.0.2 for interoperability */ 302 private static final long serialVersionUID = 3286316764910316507L; 303 304 /* 305 * Load net library into runtime, and perform initializations. 306 */ 307 static { 308 String str = GetPropertyAction.privilegedGetProperty("java.net.preferIPv6Addresses"); 309 if (str == null) { 310 preferIPv6Address = PREFER_IPV4_VALUE; 311 } else if (str.equalsIgnoreCase("true")) { 312 preferIPv6Address = PREFER_IPV6_VALUE; 313 } else if (str.equalsIgnoreCase("false")) { 314 preferIPv6Address = PREFER_IPV4_VALUE; 315 } else if (str.equalsIgnoreCase("system")) { 316 preferIPv6Address = PREFER_SYSTEM_VALUE; 317 } else { 318 preferIPv6Address = PREFER_IPV4_VALUE; 319 } 320 AccessController.doPrivileged( 321 new java.security.PrivilegedAction<>() { 322 public Void run() { 323 System.loadLibrary("net"); 324 return null; 325 } 326 }); 327 SharedSecrets.setJavaNetInetAddressAccess( 328 new JavaNetInetAddressAccess() { 329 public String getOriginalHostName(InetAddress ia) { 330 return ia.holder.getOriginalHostName(); 331 } 332 333 public InetAddress getByName(String hostName, 334 InetAddress hostAddress) 335 throws UnknownHostException 336 { 337 return InetAddress.getByName(hostName, hostAddress); 338 } 339 } 340 ); 341 init(); 342 } 343 344 /** 345 * Constructor for the Socket.accept() method. 346 * This creates an empty InetAddress, which is filled in by 347 * the accept() method. This InetAddress, however, is not 348 * put in the address cache, since it is not created by name. 349 */ 350 InetAddress() { 351 holder = new InetAddressHolder(); 352 } 353 354 /** 355 * Replaces the de-serialized object with an Inet4Address object. 356 * 357 * @return the alternate object to the de-serialized object. 358 * 359 * @throws ObjectStreamException if a new object replacing this 360 * object could not be created 361 */ 362 private Object readResolve() throws ObjectStreamException { 363 // will replace the deserialized 'this' object 364 return new Inet4Address(holder().getHostName(), holder().getAddress()); 365 } 366 367 /** 368 * Utility routine to check if the InetAddress is an 369 * IP multicast address. 370 * @return a {@code boolean} indicating if the InetAddress is 371 * an IP multicast address 372 * @since 1.1 373 */ 374 public boolean isMulticastAddress() { 375 return false; 376 } 377 378 /** 379 * Utility routine to check if the InetAddress is a wildcard address. 380 * @return a {@code boolean} indicating if the InetAddress is 381 * a wildcard address. 382 * @since 1.4 383 */ 384 public boolean isAnyLocalAddress() { 385 return false; 386 } 387 388 /** 389 * Utility routine to check if the InetAddress is a loopback address. 390 * 391 * @return a {@code boolean} indicating if the InetAddress is 392 * a loopback address; or false otherwise. 393 * @since 1.4 394 */ 395 public boolean isLoopbackAddress() { 396 return false; 397 } 398 399 /** 400 * Utility routine to check if the InetAddress is an link local address. 401 * 402 * @return a {@code boolean} indicating if the InetAddress is 403 * a link local address; or false if address is not a link local unicast address. 404 * @since 1.4 405 */ 406 public boolean isLinkLocalAddress() { 407 return false; 408 } 409 410 /** 411 * Utility routine to check if the InetAddress is a site local address. 412 * 413 * @return a {@code boolean} indicating if the InetAddress is 414 * a site local address; or false if address is not a site local unicast address. 415 * @since 1.4 416 */ 417 public boolean isSiteLocalAddress() { 418 return false; 419 } 420 421 /** 422 * Utility routine to check if the multicast address has global scope. 423 * 424 * @return a {@code boolean} indicating if the address has 425 * is a multicast address of global scope, false if it is not 426 * of global scope or it is not a multicast address 427 * @since 1.4 428 */ 429 public boolean isMCGlobal() { 430 return false; 431 } 432 433 /** 434 * Utility routine to check if the multicast address has node scope. 435 * 436 * @return a {@code boolean} indicating if the address has 437 * is a multicast address of node-local scope, false if it is not 438 * of node-local scope or it is not a multicast address 439 * @since 1.4 440 */ 441 public boolean isMCNodeLocal() { 442 return false; 443 } 444 445 /** 446 * Utility routine to check if the multicast address has link scope. 447 * 448 * @return a {@code boolean} indicating if the address has 449 * is a multicast address of link-local scope, false if it is not 450 * of link-local scope or it is not a multicast address 451 * @since 1.4 452 */ 453 public boolean isMCLinkLocal() { 454 return false; 455 } 456 457 /** 458 * Utility routine to check if the multicast address has site scope. 459 * 460 * @return a {@code boolean} indicating if the address has 461 * is a multicast address of site-local scope, false if it is not 462 * of site-local scope or it is not a multicast address 463 * @since 1.4 464 */ 465 public boolean isMCSiteLocal() { 466 return false; 467 } 468 469 /** 470 * Utility routine to check if the multicast address has organization scope. 471 * 472 * @return a {@code boolean} indicating if the address has 473 * is a multicast address of organization-local scope, 474 * false if it is not of organization-local scope 475 * or it is not a multicast address 476 * @since 1.4 477 */ 478 public boolean isMCOrgLocal() { 479 return false; 480 } 481 482 483 /** 484 * Test whether that address is reachable. Best effort is made by the 485 * implementation to try to reach the host, but firewalls and server 486 * configuration may block requests resulting in a unreachable status 487 * while some specific ports may be accessible. 488 * A typical implementation will use ICMP ECHO REQUESTs if the 489 * privilege can be obtained, otherwise it will try to establish 490 * a TCP connection on port 7 (Echo) of the destination host. 491 * <p> 492 * The timeout value, in milliseconds, indicates the maximum amount of time 493 * the try should take. If the operation times out before getting an 494 * answer, the host is deemed unreachable. A negative value will result 495 * in an IllegalArgumentException being thrown. 496 * 497 * @param timeout the time, in milliseconds, before the call aborts 498 * @return a {@code boolean} indicating if the address is reachable. 499 * @throws IOException if a network error occurs 500 * @throws IllegalArgumentException if {@code timeout} is negative. 501 * @since 1.5 502 */ 503 public boolean isReachable(int timeout) throws IOException { 504 return isReachable(null, 0 , timeout); 505 } 506 507 /** 508 * Test whether that address is reachable. Best effort is made by the 509 * implementation to try to reach the host, but firewalls and server 510 * configuration may block requests resulting in a unreachable status 511 * while some specific ports may be accessible. 512 * A typical implementation will use ICMP ECHO REQUESTs if the 513 * privilege can be obtained, otherwise it will try to establish 514 * a TCP connection on port 7 (Echo) of the destination host. 515 * <p> 516 * The {@code network interface} and {@code ttl} parameters 517 * let the caller specify which network interface the test will go through 518 * and the maximum number of hops the packets should go through. 519 * A negative value for the {@code ttl} will result in an 520 * IllegalArgumentException being thrown. 521 * <p> 522 * The timeout value, in milliseconds, indicates the maximum amount of time 523 * the try should take. If the operation times out before getting an 524 * answer, the host is deemed unreachable. A negative value will result 525 * in an IllegalArgumentException being thrown. 526 * 527 * @param netif the NetworkInterface through which the 528 * test will be done, or null for any interface 529 * @param ttl the maximum numbers of hops to try or 0 for the 530 * default 531 * @param timeout the time, in milliseconds, before the call aborts 532 * @throws IllegalArgumentException if either {@code timeout} 533 * or {@code ttl} are negative. 534 * @return a {@code boolean} indicating if the address is reachable. 535 * @throws IOException if a network error occurs 536 * @since 1.5 537 */ 538 public boolean isReachable(NetworkInterface netif, int ttl, 539 int timeout) throws IOException { 540 if (ttl < 0) 541 throw new IllegalArgumentException("ttl can't be negative"); 542 if (timeout < 0) 543 throw new IllegalArgumentException("timeout can't be negative"); 544 545 return impl.isReachable(this, timeout, netif, ttl); 546 } 547 548 /** 549 * Gets the host name for this IP address. 550 * 551 * <p>If this InetAddress was created with a host name, 552 * this host name will be remembered and returned; 553 * otherwise, a reverse name lookup will be performed 554 * and the result will be returned based on the system 555 * configured name lookup service. If a lookup of the name service 556 * is required, call 557 * {@link #getCanonicalHostName() getCanonicalHostName}. 558 * 559 * <p>If there is a security manager, its 560 * {@code checkConnect} method is first called 561 * with the hostname and {@code -1} 562 * as its arguments to see if the operation is allowed. 563 * If the operation is not allowed, it will return 564 * the textual representation of the IP address. 565 * 566 * @return the host name for this IP address, or if the operation 567 * is not allowed by the security check, the textual 568 * representation of the IP address. 569 * 570 * @see InetAddress#getCanonicalHostName 571 * @see SecurityManager#checkConnect 572 */ 573 public String getHostName() { 574 return getHostName(true); 575 } 576 577 /** 578 * Returns the hostname for this address. 579 * If the host is equal to null, then this address refers to any 580 * of the local machine's available network addresses. 581 * this is package private so SocketPermission can make calls into 582 * here without a security check. 583 * 584 * <p>If there is a security manager, this method first 585 * calls its {@code checkConnect} method 586 * with the hostname and {@code -1} 587 * as its arguments to see if the calling code is allowed to know 588 * the hostname for this IP address, i.e., to connect to the host. 589 * If the operation is not allowed, it will return 590 * the textual representation of the IP address. 591 * 592 * @return the host name for this IP address, or if the operation 593 * is not allowed by the security check, the textual 594 * representation of the IP address. 595 * 596 * @param check make security check if true 597 * 598 * @see SecurityManager#checkConnect 599 */ 600 String getHostName(boolean check) { 601 if (holder().getHostName() == null) { 602 holder().hostName = InetAddress.getHostFromNameService(this, check); 603 } 604 return holder().getHostName(); 605 } 606 607 /** 608 * Gets the fully qualified domain name for this IP address. 609 * Best effort method, meaning we may not be able to return 610 * the FQDN depending on the underlying system configuration. 611 * 612 * <p>If there is a security manager, this method first 613 * calls its {@code checkConnect} method 614 * with the hostname and {@code -1} 615 * as its arguments to see if the calling code is allowed to know 616 * the hostname for this IP address, i.e., to connect to the host. 617 * If the operation is not allowed, it will return 618 * the textual representation of the IP address. 619 * 620 * @return the fully qualified domain name for this IP address, 621 * or if the operation is not allowed by the security check, 622 * the textual representation of the IP address. 623 * 624 * @see SecurityManager#checkConnect 625 * 626 * @since 1.4 627 */ 628 public String getCanonicalHostName() { 629 String value = canonicalHostName; 630 if (value == null) 631 canonicalHostName = value = 632 InetAddress.getHostFromNameService(this, true); 633 return value; 634 } 635 636 /** 637 * Returns the hostname for this address. 638 * 639 * <p>If there is a security manager, this method first 640 * calls its {@code checkConnect} method 641 * with the hostname and {@code -1} 642 * as its arguments to see if the calling code is allowed to know 643 * the hostname for this IP address, i.e., to connect to the host. 644 * If the operation is not allowed, it will return 645 * the textual representation of the IP address. 646 * 647 * @return the host name for this IP address, or if the operation 648 * is not allowed by the security check, the textual 649 * representation of the IP address. 650 * 651 * @param check make security check if true 652 * 653 * @see SecurityManager#checkConnect 654 */ 655 private static String getHostFromNameService(InetAddress addr, boolean check) { 656 String host = null; 657 try { 658 // first lookup the hostname 659 host = nameService.getHostByAddr(addr.getAddress()); 660 661 /* check to see if calling code is allowed to know 662 * the hostname for this IP address, ie, connect to the host 663 */ 664 if (check) { 665 SecurityManager sec = System.getSecurityManager(); 666 if (sec != null) { 667 sec.checkConnect(host, -1); 668 } 669 } 670 671 /* now get all the IP addresses for this hostname, 672 * and make sure one of them matches the original IP 673 * address. We do this to try and prevent spoofing. 674 */ 675 676 InetAddress[] arr = InetAddress.getAllByName0(host, check); 677 boolean ok = false; 678 679 if(arr != null) { 680 for(int i = 0; !ok && i < arr.length; i++) { 681 ok = addr.equals(arr[i]); 682 } 683 } 684 685 //XXX: if it looks a spoof just return the address? 686 if (!ok) { 687 host = addr.getHostAddress(); 688 return host; 689 } 690 } catch (SecurityException e) { 691 host = addr.getHostAddress(); 692 } catch (UnknownHostException e) { 693 host = addr.getHostAddress(); 694 // let next provider resolve the hostname 695 } 696 return host; 697 } 698 699 /** 700 * Returns the raw IP address of this {@code InetAddress} 701 * object. The result is in network byte order: the highest order 702 * byte of the address is in {@code getAddress()[0]}. 703 * 704 * @return the raw IP address of this object. 705 */ 706 public byte[] getAddress() { 707 return null; 708 } 709 710 /** 711 * Returns the IP address string in textual presentation. 712 * 713 * @return the raw IP address in a string format. 714 * @since 1.0.2 715 */ 716 public String getHostAddress() { 717 return null; 718 } 719 720 /** 721 * Returns a hashcode for this IP address. 722 * 723 * @return a hash code value for this IP address. 724 */ 725 public int hashCode() { 726 return -1; 727 } 728 729 /** 730 * Compares this object against the specified object. 731 * The result is {@code true} if and only if the argument is 732 * not {@code null} and it represents the same IP address as 733 * this object. 734 * <p> 735 * Two instances of {@code InetAddress} represent the same IP 736 * address if the length of the byte arrays returned by 737 * {@code getAddress} is the same for both, and each of the 738 * array components is the same for the byte arrays. 739 * 740 * @param obj the object to compare against. 741 * @return {@code true} if the objects are the same; 742 * {@code false} otherwise. 743 * @see java.net.InetAddress#getAddress() 744 */ 745 public boolean equals(Object obj) { 746 return false; 747 } 748 749 /** 750 * Converts this IP address to a {@code String}. The 751 * string returned is of the form: hostname / literal IP 752 * address. 753 * 754 * If the host name is unresolved, no reverse name service lookup 755 * is performed. The hostname part will be represented by an empty string. 756 * 757 * @return a string representation of this IP address. 758 */ 759 public String toString() { 760 String hostName = holder().getHostName(); 761 return Objects.toString(hostName, "") 762 + "/" + getHostAddress(); 763 } 764 765 // mapping from host name to Addresses - either NameServiceAddresses (while 766 // still being looked-up by NameService(s)) or CachedAddresses when cached 767 private static final ConcurrentMap<String, Addresses> cache = 768 new ConcurrentHashMap<>(); 769 770 // CachedAddresses that have to expire are kept ordered in this NavigableSet 771 // which is scanned on each access 772 private static final NavigableSet<CachedAddresses> expirySet = 773 new ConcurrentSkipListSet<>(); 774 775 // common interface 776 private interface Addresses { 777 InetAddress[] get() throws UnknownHostException; 778 } 779 780 // a holder for cached addresses with required metadata 781 private static final class CachedAddresses implements Addresses, Comparable<CachedAddresses> { 782 private static final AtomicLong seq = new AtomicLong(); 783 final String host; 784 final InetAddress[] inetAddresses; 785 final long expiryTime; // time of expiry (in terms of System.nanoTime()) 786 final long id = seq.incrementAndGet(); // each instance is unique 787 788 CachedAddresses(String host, InetAddress[] inetAddresses, long expiryTime) { 789 this.host = host; 790 this.inetAddresses = inetAddresses; 791 this.expiryTime = expiryTime; 792 } 793 794 @Override 795 public InetAddress[] get() throws UnknownHostException { 796 if (inetAddresses == null) { 797 throw new UnknownHostException(host); 798 } 799 return inetAddresses; 800 } 801 802 @Override 803 public int compareTo(CachedAddresses other) { 804 // natural order is expiry time - 805 // compare difference of expiry times rather than 806 // expiry times directly, to avoid possible overflow. 807 // (see System.nanoTime() recommendations...) 808 long diff = this.expiryTime - other.expiryTime; 809 if (diff < 0L) return -1; 810 if (diff > 0L) return 1; 811 // ties are broken using unique id 812 return Long.compare(this.id, other.id); 813 } 814 } 815 816 // a name service lookup based Addresses implementation which replaces itself 817 // in cache when the result is obtained 818 private static final class NameServiceAddresses implements Addresses { 819 private final String host; 820 private final InetAddress reqAddr; 821 822 NameServiceAddresses(String host, InetAddress reqAddr) { 823 this.host = host; 824 this.reqAddr = reqAddr; 825 } 826 827 @Override 828 public InetAddress[] get() throws UnknownHostException { 829 Addresses addresses; 830 // only one thread is doing lookup to name service 831 // for particular host at any time. 832 synchronized (this) { 833 // re-check that we are still us + re-install us if slot empty 834 addresses = cache.putIfAbsent(host, this); 835 if (addresses == null) { 836 // this can happen when we were replaced by CachedAddresses in 837 // some other thread, then CachedAddresses expired and were 838 // removed from cache while we were waiting for lock... 839 addresses = this; 840 } 841 // still us ? 842 if (addresses == this) { 843 // lookup name services 844 InetAddress[] inetAddresses; 845 UnknownHostException ex; 846 int cachePolicy; 847 try { 848 inetAddresses = getAddressesFromNameService(host, reqAddr); 849 ex = null; 850 cachePolicy = InetAddressCachePolicy.get(); 851 } catch (UnknownHostException uhe) { 852 inetAddresses = null; 853 ex = uhe; 854 cachePolicy = InetAddressCachePolicy.getNegative(); 855 } 856 // remove or replace us with cached addresses according to cachePolicy 857 if (cachePolicy == InetAddressCachePolicy.NEVER) { 858 cache.remove(host, this); 859 } else { 860 CachedAddresses cachedAddresses = new CachedAddresses( 861 host, 862 inetAddresses, 863 cachePolicy == InetAddressCachePolicy.FOREVER 864 ? 0L 865 // cachePolicy is in [s] - we need [ns] 866 : System.nanoTime() + 1000_000_000L * cachePolicy 867 ); 868 if (cache.replace(host, this, cachedAddresses) && 869 cachePolicy != InetAddressCachePolicy.FOREVER) { 870 // schedule expiry 871 expirySet.add(cachedAddresses); 872 } 873 } 874 if (inetAddresses == null) { 875 throw ex == null ? new UnknownHostException(host) : ex; 876 } 877 return inetAddresses; 878 } 879 // else addresses != this 880 } 881 // delegate to different addresses when we are already replaced 882 // but outside of synchronized block to avoid any chance of dead-locking 883 return addresses.get(); 884 } 885 } 886 887 /** 888 * NameService provides host and address lookup service 889 * 890 * @since 9 891 */ 892 private interface NameService { 893 894 /** 895 * Lookup a host mapping by name. Retrieve the IP addresses 896 * associated with a host 897 * 898 * @param host the specified hostname 899 * @return array of IP addresses for the requested host 900 * @throws UnknownHostException 901 * if no IP address for the {@code host} could be found 902 */ 903 InetAddress[] lookupAllHostAddr(String host) 904 throws UnknownHostException; 905 906 /** 907 * Lookup the host corresponding to the IP address provided 908 * 909 * @param addr byte array representing an IP address 910 * @return {@code String} representing the host name mapping 911 * @throws UnknownHostException 912 * if no host found for the specified IP address 913 */ 914 String getHostByAddr(byte[] addr) throws UnknownHostException; 915 916 } 917 918 /** 919 * The default NameService implementation, which delegates to the underlying 920 * OS network libraries to resolve host address mappings. 921 * 922 * @since 9 923 */ 924 private static final class PlatformNameService implements NameService { 925 926 public InetAddress[] lookupAllHostAddr(String host) 927 throws UnknownHostException 928 { 929 return impl.lookupAllHostAddr(host); 930 } 931 932 public String getHostByAddr(byte[] addr) 933 throws UnknownHostException 934 { 935 return impl.getHostByAddr(addr); 936 } 937 } 938 939 /** 940 * The HostsFileNameService provides host address mapping 941 * by reading the entries in a hosts file, which is specified by 942 * {@code jdk.net.hosts.file} system property 943 * 944 * <p>The file format is that which corresponds with the /etc/hosts file 945 * IP Address host alias list. 946 * 947 * <p>When the file lookup is enabled it replaces the default NameService 948 * implementation 949 * 950 * @since 9 951 */ 952 private static final class HostsFileNameService implements NameService { 953 954 private final String hostsFile; 955 956 public HostsFileNameService (String hostsFileName) { 957 this.hostsFile = hostsFileName; 958 } 959 960 private String addrToString(byte addr[]) { 961 String stringifiedAddress = null; 962 963 if (addr.length == Inet4Address.INADDRSZ) { 964 stringifiedAddress = Inet4Address.numericToTextFormat(addr); 965 } else { // treat as an IPV6 jobby 966 byte[] newAddr 967 = IPAddressUtil.convertFromIPv4MappedAddress(addr); 968 if (newAddr != null) { 969 stringifiedAddress = Inet4Address.numericToTextFormat(addr); 970 } else { 971 stringifiedAddress = Inet6Address.numericToTextFormat(addr); 972 } 973 } 974 return stringifiedAddress; 975 } 976 977 /** 978 * Lookup the host name corresponding to the IP address provided. 979 * Search the configured host file a host name corresponding to 980 * the specified IP address. 981 * 982 * @param addr byte array representing an IP address 983 * @return {@code String} representing the host name mapping 984 * @throws UnknownHostException 985 * if no host found for the specified IP address 986 */ 987 @Override 988 public String getHostByAddr(byte[] addr) throws UnknownHostException { 989 String hostEntry; 990 String host = null; 991 992 try (Scanner hostsFileScanner = new Scanner(new File(hostsFile), "UTF-8")) { 993 while (hostsFileScanner.hasNextLine()) { 994 hostEntry = hostsFileScanner.nextLine(); 995 if (!hostEntry.startsWith("#")) { 996 hostEntry = removeComments(hostEntry); 997 String[] mapping = hostEntry.split("\\s+"); 998 if (mapping.length >= 2 && 999 Arrays.equals(addr, createAddressByteArray(mapping[0]))) { 1000 host = mapping[1]; 1001 break; 1002 } 1003 } 1004 } 1005 } catch (FileNotFoundException e) { 1006 throw new UnknownHostException("Unable to resolve address " 1007 + Arrays.toString(addr) + " as hosts file " + hostsFile 1008 + " not found "); 1009 } 1010 1011 if ((host == null) || (host.isEmpty()) || (host.equals(" "))) { 1012 throw new UnknownHostException("Requested address " 1013 + Arrays.toString(addr) 1014 + " resolves to an invalid entry in hosts file " 1015 + hostsFile); 1016 } 1017 return host; 1018 } 1019 1020 /** 1021 * <p>Lookup a host mapping by name. Retrieve the IP addresses 1022 * associated with a host. 1023 * 1024 * <p>Search the configured hosts file for the addresses associated 1025 * with the specified host name. 1026 * 1027 * @param host the specified hostname 1028 * @return array of IP addresses for the requested host 1029 * @throws UnknownHostException 1030 * if no IP address for the {@code host} could be found 1031 */ 1032 public InetAddress[] lookupAllHostAddr(String host) 1033 throws UnknownHostException { 1034 String hostEntry; 1035 String addrStr = null; 1036 InetAddress[] res = null; 1037 byte addr[] = new byte[4]; 1038 ArrayList<InetAddress> inetAddresses = null; 1039 1040 // lookup the file and create a list InetAddress for the specified host 1041 try (Scanner hostsFileScanner = new Scanner(new File(hostsFile), "UTF-8")) { 1042 while (hostsFileScanner.hasNextLine()) { 1043 hostEntry = hostsFileScanner.nextLine(); 1044 if (!hostEntry.startsWith("#")) { 1045 hostEntry = removeComments(hostEntry); 1046 if (hostEntry.contains(host)) { 1047 addrStr = extractHostAddr(hostEntry, host); 1048 if ((addrStr != null) && (!addrStr.isEmpty())) { 1049 addr = createAddressByteArray(addrStr); 1050 if (inetAddresses == null) { 1051 inetAddresses = new ArrayList<>(1); 1052 } 1053 if (addr != null) { 1054 inetAddresses.add(InetAddress.getByAddress(host, addr)); 1055 } 1056 } 1057 } 1058 } 1059 } 1060 } catch (FileNotFoundException e) { 1061 throw new UnknownHostException("Unable to resolve host " + host 1062 + " as hosts file " + hostsFile + " not found "); 1063 } 1064 1065 if (inetAddresses != null) { 1066 res = inetAddresses.toArray(new InetAddress[inetAddresses.size()]); 1067 } else { 1068 throw new UnknownHostException("Unable to resolve host " + host 1069 + " in hosts file " + hostsFile); 1070 } 1071 return res; 1072 } 1073 1074 private String removeComments(String hostsEntry) { 1075 String filteredEntry = hostsEntry; 1076 int hashIndex; 1077 1078 if ((hashIndex = hostsEntry.indexOf("#")) != -1) { 1079 filteredEntry = hostsEntry.substring(0, hashIndex); 1080 } 1081 return filteredEntry; 1082 } 1083 1084 private byte [] createAddressByteArray(String addrStr) { 1085 byte[] addrArray; 1086 // check if IPV4 address - most likely 1087 addrArray = IPAddressUtil.textToNumericFormatV4(addrStr); 1088 if (addrArray == null) { 1089 addrArray = IPAddressUtil.textToNumericFormatV6(addrStr); 1090 } 1091 return addrArray; 1092 } 1093 1094 /** host to ip address mapping */ 1095 private String extractHostAddr(String hostEntry, String host) { 1096 String[] mapping = hostEntry.split("\\s+"); 1097 String hostAddr = null; 1098 1099 if (mapping.length >= 2) { 1100 // look at the host aliases 1101 for (int i = 1; i < mapping.length; i++) { 1102 if (mapping[i].equalsIgnoreCase(host)) { 1103 hostAddr = mapping[0]; 1104 } 1105 } 1106 } 1107 return hostAddr; 1108 } 1109 } 1110 1111 static final InetAddressImpl impl; 1112 1113 static { 1114 // create the impl 1115 impl = InetAddressImplFactory.create(); 1116 1117 // create name service 1118 nameService = createNameService(); 1119 } 1120 1121 /** 1122 * Create an instance of the NameService interface based on 1123 * the setting of the {@code jdk.net.hosts.file} system property. 1124 * 1125 * <p>The default NameService is the PlatformNameService, which typically 1126 * delegates name and address resolution calls to the underlying 1127 * OS network libraries. 1128 * 1129 * <p> A HostsFileNameService is created if the {@code jdk.net.hosts.file} 1130 * system property is set. If the specified file doesn't exist, the name or 1131 * address lookup will result in an UnknownHostException. Thus, non existent 1132 * hosts file is handled as if the file is empty. 1133 * 1134 * @return a NameService 1135 */ 1136 private static NameService createNameService() { 1137 1138 String hostsFileName = 1139 GetPropertyAction.privilegedGetProperty("jdk.net.hosts.file"); 1140 NameService theNameService; 1141 if (hostsFileName != null) { 1142 theNameService = new HostsFileNameService(hostsFileName); 1143 } else { 1144 theNameService = new PlatformNameService(); 1145 } 1146 return theNameService; 1147 } 1148 1149 /** 1150 * Creates an InetAddress based on the provided host name and IP address. 1151 * No name service is checked for the validity of the address. 1152 * 1153 * <p> The host name can either be a machine name, such as 1154 * "{@code www.example.com}", or a textual representation of its IP 1155 * address. 1156 * <p> No validity checking is done on the host name either. 1157 * 1158 * <p> If addr specifies an IPv4 address an instance of Inet4Address 1159 * will be returned; otherwise, an instance of Inet6Address 1160 * will be returned. 1161 * 1162 * <p> IPv4 address byte array must be 4 bytes long and IPv6 byte array 1163 * must be 16 bytes long 1164 * 1165 * @param host the specified host 1166 * @param addr the raw IP address in network byte order 1167 * @return an InetAddress object created from the raw IP address. 1168 * @exception UnknownHostException if IP address is of illegal length 1169 * @since 1.4 1170 */ 1171 public static InetAddress getByAddress(String host, byte[] addr) 1172 throws UnknownHostException { 1173 if (host != null && !host.isEmpty() && host.charAt(0) == '[') { 1174 if (host.charAt(host.length()-1) == ']') { 1175 host = host.substring(1, host.length() -1); 1176 } 1177 } 1178 if (addr != null) { 1179 if (addr.length == Inet4Address.INADDRSZ) { 1180 return new Inet4Address(host, addr); 1181 } else if (addr.length == Inet6Address.INADDRSZ) { 1182 byte[] newAddr 1183 = IPAddressUtil.convertFromIPv4MappedAddress(addr); 1184 if (newAddr != null) { 1185 return new Inet4Address(host, newAddr); 1186 } else { 1187 return new Inet6Address(host, addr); 1188 } 1189 } 1190 } 1191 throw new UnknownHostException("addr is of illegal length"); 1192 } 1193 1194 1195 /** 1196 * Determines the IP address of a host, given the host's name. 1197 * 1198 * <p> The host name can either be a machine name, such as 1199 * "{@code www.example.com}", or a textual representation of its 1200 * IP address. If a literal IP address is supplied, only the 1201 * validity of the address format is checked. 1202 * 1203 * <p> For {@code host} specified in literal IPv6 address, 1204 * either the form defined in RFC 2732 or the literal IPv6 address 1205 * format defined in RFC 2373 is accepted. IPv6 scoped addresses are also 1206 * supported. See <a href="Inet6Address.html#scoped">here</a> for a description of IPv6 1207 * scoped addresses. 1208 * 1209 * <p> If the host is {@code null} or {@code host.length()} is equal 1210 * to zero, then an {@code InetAddress} representing an address of the 1211 * loopback interface is returned. 1212 * See <a href="http://www.ietf.org/rfc/rfc3330.txt">RFC 3330</a> 1213 * section 2 and <a href="http://www.ietf.org/rfc/rfc2373.txt">RFC 2373</a> 1214 * section 2.5.3. 1215 * 1216 * <p> If there is a security manager, and {@code host} is not {@code null} 1217 * or {@code host.length() } is not equal to zero, the security manager's 1218 * {@code checkConnect} method is called with the hostname and {@code -1} 1219 * as its arguments to determine if the operation is allowed. 1220 * 1221 * @param host the specified host, or {@code null}. 1222 * @return an IP address for the given host name. 1223 * @exception UnknownHostException if no IP address for the 1224 * {@code host} could be found, or if a scope_id was specified 1225 * for a global IPv6 address. 1226 * @exception SecurityException if a security manager exists 1227 * and its checkConnect method doesn't allow the operation 1228 */ 1229 public static InetAddress getByName(String host) 1230 throws UnknownHostException { 1231 return InetAddress.getAllByName(host)[0]; 1232 } 1233 1234 // called from deployment cache manager 1235 private static InetAddress getByName(String host, InetAddress reqAddr) 1236 throws UnknownHostException { 1237 return InetAddress.getAllByName(host, reqAddr)[0]; 1238 } 1239 1240 /** 1241 * Given the name of a host, returns an array of its IP addresses, 1242 * based on the configured name service on the system. 1243 * 1244 * <p> The host name can either be a machine name, such as 1245 * "{@code www.example.com}", or a textual representation of its IP 1246 * address. If a literal IP address is supplied, only the 1247 * validity of the address format is checked. 1248 * 1249 * <p> For {@code host} specified in <i>literal IPv6 address</i>, 1250 * either the form defined in RFC 2732 or the literal IPv6 address 1251 * format defined in RFC 2373 is accepted. A literal IPv6 address may 1252 * also be qualified by appending a scoped zone identifier or scope_id. 1253 * The syntax and usage of scope_ids is described 1254 * <a href="Inet6Address.html#scoped">here</a>. 1255 * 1256 * <p> If the host is {@code null} or {@code host.length()} is equal 1257 * to zero, then an {@code InetAddress} representing an address of the 1258 * loopback interface is returned. 1259 * See <a href="http://www.ietf.org/rfc/rfc3330.txt">RFC 3330</a> 1260 * section 2 and <a href="http://www.ietf.org/rfc/rfc2373.txt">RFC 2373</a> 1261 * section 2.5.3. </p> 1262 * 1263 * <p> If there is a security manager, and {@code host} is not {@code null} 1264 * or {@code host.length() } is not equal to zero, the security manager's 1265 * {@code checkConnect} method is called with the hostname and {@code -1} 1266 * as its arguments to determine if the operation is allowed. 1267 * 1268 * @param host the name of the host, or {@code null}. 1269 * @return an array of all the IP addresses for a given host name. 1270 * 1271 * @exception UnknownHostException if no IP address for the 1272 * {@code host} could be found, or if a scope_id was specified 1273 * for a global IPv6 address. 1274 * @exception SecurityException if a security manager exists and its 1275 * {@code checkConnect} method doesn't allow the operation. 1276 * 1277 * @see SecurityManager#checkConnect 1278 */ 1279 public static InetAddress[] getAllByName(String host) 1280 throws UnknownHostException { 1281 return getAllByName(host, null); 1282 } 1283 1284 private static InetAddress[] getAllByName(String host, InetAddress reqAddr) 1285 throws UnknownHostException { 1286 1287 if (host == null || host.isEmpty()) { 1288 InetAddress[] ret = new InetAddress[1]; 1289 ret[0] = impl.loopbackAddress(); 1290 return ret; 1291 } 1292 1293 boolean ipv6Expected = false; 1294 if (host.charAt(0) == '[') { 1295 // This is supposed to be an IPv6 literal 1296 if (host.length() > 2 && host.charAt(host.length()-1) == ']') { 1297 host = host.substring(1, host.length() -1); 1298 ipv6Expected = true; 1299 } else { 1300 // This was supposed to be a IPv6 address, but it's not! 1301 throw new UnknownHostException(host + ": invalid IPv6 address"); 1302 } 1303 } 1304 1305 // if host is an IP address, we won't do further lookup 1306 if (Character.digit(host.charAt(0), 16) != -1 1307 || (host.charAt(0) == ':')) { 1308 byte[] addr = null; 1309 int numericZone = -1; 1310 String ifname = null; 1311 // see if it is IPv4 address 1312 addr = IPAddressUtil.textToNumericFormatV4(host); 1313 if (addr == null) { 1314 // This is supposed to be an IPv6 literal 1315 // Check if a numeric or string zone id is present 1316 int pos; 1317 if ((pos=host.indexOf ('%')) != -1) { 1318 numericZone = checkNumericZone (host); 1319 if (numericZone == -1) { /* remainder of string must be an ifname */ 1320 ifname = host.substring (pos+1); 1321 } 1322 } 1323 if ((addr = IPAddressUtil.textToNumericFormatV6(host)) == null && host.contains(":")) { 1324 throw new UnknownHostException(host + ": invalid IPv6 address"); 1325 } 1326 } else if (ipv6Expected) { 1327 // Means an IPv4 literal between brackets! 1328 throw new UnknownHostException("["+host+"]"); 1329 } 1330 InetAddress[] ret = new InetAddress[1]; 1331 if(addr != null) { 1332 if (addr.length == Inet4Address.INADDRSZ) { 1333 ret[0] = new Inet4Address(null, addr); 1334 } else { 1335 if (ifname != null) { 1336 ret[0] = new Inet6Address(null, addr, ifname); 1337 } else { 1338 ret[0] = new Inet6Address(null, addr, numericZone); 1339 } 1340 } 1341 return ret; 1342 } 1343 } else if (ipv6Expected) { 1344 // We were expecting an IPv6 Literal, but got something else 1345 throw new UnknownHostException("["+host+"]"); 1346 } 1347 return getAllByName0(host, reqAddr, true, true); 1348 } 1349 1350 /** 1351 * Returns the loopback address. 1352 * <p> 1353 * The InetAddress returned will represent the IPv4 1354 * loopback address, 127.0.0.1, or the IPv6 loopback 1355 * address, ::1. The IPv4 loopback address returned 1356 * is only one of many in the form 127.*.*.* 1357 * 1358 * @return the InetAddress loopback instance. 1359 * @since 1.7 1360 */ 1361 public static InetAddress getLoopbackAddress() { 1362 return impl.loopbackAddress(); 1363 } 1364 1365 1366 /** 1367 * check if the literal address string has %nn appended 1368 * returns -1 if not, or the numeric value otherwise. 1369 * 1370 * %nn may also be a string that represents the displayName of 1371 * a currently available NetworkInterface. 1372 */ 1373 private static int checkNumericZone (String s) throws UnknownHostException { 1374 int percent = s.indexOf ('%'); 1375 int slen = s.length(); 1376 int digit, zone=0; 1377 if (percent == -1) { 1378 return -1; 1379 } 1380 for (int i=percent+1; i<slen; i++) { 1381 char c = s.charAt(i); 1382 if (c == ']') { 1383 if (i == percent+1) { 1384 /* empty per-cent field */ 1385 return -1; 1386 } 1387 break; 1388 } 1389 if ((digit = Character.digit (c, 10)) < 0) { 1390 return -1; 1391 } 1392 zone = (zone * 10) + digit; 1393 } 1394 return zone; 1395 } 1396 1397 private static InetAddress[] getAllByName0 (String host) 1398 throws UnknownHostException 1399 { 1400 return getAllByName0(host, true); 1401 } 1402 1403 /** 1404 * package private so SocketPermission can call it 1405 */ 1406 static InetAddress[] getAllByName0 (String host, boolean check) 1407 throws UnknownHostException { 1408 return getAllByName0 (host, null, check, true); 1409 } 1410 1411 /** 1412 * Designated lookup method. 1413 * 1414 * @param host host name to look up 1415 * @param reqAddr requested address to be the 1st in returned array 1416 * @param check perform security check 1417 * @param useCache use cached value if not expired else always 1418 * perform name service lookup (and cache the result) 1419 * @return array of InetAddress(es) 1420 * @throws UnknownHostException if host name is not found 1421 */ 1422 private static InetAddress[] getAllByName0(String host, 1423 InetAddress reqAddr, 1424 boolean check, 1425 boolean useCache) 1426 throws UnknownHostException { 1427 1428 /* If it gets here it is presumed to be a hostname */ 1429 1430 /* make sure the connection to the host is allowed, before we 1431 * give out a hostname 1432 */ 1433 if (check) { 1434 SecurityManager security = System.getSecurityManager(); 1435 if (security != null) { 1436 security.checkConnect(host, -1); 1437 } 1438 } 1439 1440 // remove expired addresses from cache - expirySet keeps them ordered 1441 // by expiry time so we only need to iterate the prefix of the NavigableSet... 1442 long now = System.nanoTime(); 1443 for (CachedAddresses caddrs : expirySet) { 1444 // compare difference of time instants rather than 1445 // time instants directly, to avoid possible overflow. 1446 // (see System.nanoTime() recommendations...) 1447 if ((caddrs.expiryTime - now) < 0L) { 1448 // ConcurrentSkipListSet uses weakly consistent iterator, 1449 // so removing while iterating is OK... 1450 if (expirySet.remove(caddrs)) { 1451 // ... remove from cache 1452 cache.remove(caddrs.host, caddrs); 1453 } 1454 } else { 1455 // we encountered 1st element that expires in future 1456 break; 1457 } 1458 } 1459 1460 // look-up or remove from cache 1461 Addresses addrs; 1462 if (useCache) { 1463 addrs = cache.get(host); 1464 } else { 1465 addrs = cache.remove(host); 1466 if (addrs != null) { 1467 if (addrs instanceof CachedAddresses) { 1468 // try removing from expirySet too if CachedAddresses 1469 expirySet.remove(addrs); 1470 } 1471 addrs = null; 1472 } 1473 } 1474 1475 if (addrs == null) { 1476 // create a NameServiceAddresses instance which will look up 1477 // the name service and install it within cache... 1478 Addresses oldAddrs = cache.putIfAbsent( 1479 host, 1480 addrs = new NameServiceAddresses(host, reqAddr) 1481 ); 1482 if (oldAddrs != null) { // lost putIfAbsent race 1483 addrs = oldAddrs; 1484 } 1485 } 1486 1487 // ask Addresses to get an array of InetAddress(es) and clone it 1488 return addrs.get().clone(); 1489 } 1490 1491 static InetAddress[] getAddressesFromNameService(String host, InetAddress reqAddr) 1492 throws UnknownHostException 1493 { 1494 InetAddress[] addresses = null; 1495 UnknownHostException ex = null; 1496 1497 try { 1498 addresses = nameService.lookupAllHostAddr(host); 1499 } catch (UnknownHostException uhe) { 1500 if (host.equalsIgnoreCase("localhost")) { 1501 addresses = new InetAddress[] { impl.loopbackAddress() }; 1502 } 1503 else { 1504 ex = uhe; 1505 } 1506 } 1507 1508 if (addresses == null) { 1509 throw ex == null ? new UnknownHostException(host) : ex; 1510 } 1511 1512 // More to do? 1513 if (reqAddr != null && addresses.length > 1 && !addresses[0].equals(reqAddr)) { 1514 // Find it? 1515 int i = 1; 1516 for (; i < addresses.length; i++) { 1517 if (addresses[i].equals(reqAddr)) { 1518 break; 1519 } 1520 } 1521 // Rotate 1522 if (i < addresses.length) { 1523 InetAddress tmp, tmp2 = reqAddr; 1524 for (int j = 0; j < i; j++) { 1525 tmp = addresses[j]; 1526 addresses[j] = tmp2; 1527 tmp2 = tmp; 1528 } 1529 addresses[i] = tmp2; 1530 } 1531 } 1532 1533 return addresses; 1534 } 1535 1536 /** 1537 * Returns an {@code InetAddress} object given the raw IP address . 1538 * The argument is in network byte order: the highest order 1539 * byte of the address is in {@code getAddress()[0]}. 1540 * 1541 * <p> This method doesn't block, i.e. no reverse name service lookup 1542 * is performed. 1543 * 1544 * <p> IPv4 address byte array must be 4 bytes long and IPv6 byte array 1545 * must be 16 bytes long 1546 * 1547 * @param addr the raw IP address in network byte order 1548 * @return an InetAddress object created from the raw IP address. 1549 * @exception UnknownHostException if IP address is of illegal length 1550 * @since 1.4 1551 */ 1552 public static InetAddress getByAddress(byte[] addr) 1553 throws UnknownHostException { 1554 return getByAddress(null, addr); 1555 } 1556 1557 private static final class CachedLocalHost { 1558 final String host; 1559 final InetAddress addr; 1560 final long expiryTime = System.nanoTime() + 5000_000_000L; // now + 5s; 1561 1562 CachedLocalHost(String host, InetAddress addr) { 1563 this.host = host; 1564 this.addr = addr; 1565 } 1566 } 1567 1568 private static volatile CachedLocalHost cachedLocalHost; 1569 1570 /** 1571 * Returns the address of the local host. This is achieved by retrieving 1572 * the name of the host from the system, then resolving that name into 1573 * an {@code InetAddress}. 1574 * 1575 * <P>Note: The resolved address may be cached for a short period of time. 1576 * </P> 1577 * 1578 * <p>If there is a security manager, its 1579 * {@code checkConnect} method is called 1580 * with the local host name and {@code -1} 1581 * as its arguments to see if the operation is allowed. 1582 * If the operation is not allowed, an InetAddress representing 1583 * the loopback address is returned. 1584 * 1585 * @return the address of the local host. 1586 * 1587 * @exception UnknownHostException if the local host name could not 1588 * be resolved into an address. 1589 * 1590 * @see SecurityManager#checkConnect 1591 * @see java.net.InetAddress#getByName(java.lang.String) 1592 */ 1593 public static InetAddress getLocalHost() throws UnknownHostException { 1594 1595 SecurityManager security = System.getSecurityManager(); 1596 try { 1597 // is cached data still valid? 1598 CachedLocalHost clh = cachedLocalHost; 1599 if (clh != null && (clh.expiryTime - System.nanoTime()) >= 0L) { 1600 if (security != null) { 1601 security.checkConnect(clh.host, -1); 1602 } 1603 return clh.addr; 1604 } 1605 1606 String local = impl.getLocalHostName(); 1607 1608 if (security != null) { 1609 security.checkConnect(local, -1); 1610 } 1611 1612 InetAddress localAddr; 1613 if (local.equals("localhost")) { 1614 // shortcut for "localhost" host name 1615 localAddr = impl.loopbackAddress(); 1616 } else { 1617 // call getAllByName0 without security checks and 1618 // without using cached data 1619 try { 1620 localAddr = getAllByName0(local, null, false, false)[0]; 1621 } catch (UnknownHostException uhe) { 1622 // Rethrow with a more informative error message. 1623 UnknownHostException uhe2 = 1624 new UnknownHostException(local + ": " + 1625 uhe.getMessage()); 1626 uhe2.initCause(uhe); 1627 throw uhe2; 1628 } 1629 } 1630 cachedLocalHost = new CachedLocalHost(local, localAddr); 1631 return localAddr; 1632 } catch (java.lang.SecurityException e) { 1633 return impl.loopbackAddress(); 1634 } 1635 } 1636 1637 /** 1638 * Perform class load-time initializations. 1639 */ 1640 private static native void init(); 1641 1642 1643 /* 1644 * Returns the InetAddress representing anyLocalAddress 1645 * (typically 0.0.0.0 or ::0) 1646 */ 1647 static InetAddress anyLocalAddress() { 1648 return impl.anyLocalAddress(); 1649 } 1650 1651 /* 1652 * Load and instantiate an underlying impl class 1653 */ 1654 static InetAddressImpl loadImpl(String implName) { 1655 Object impl = null; 1656 1657 /* 1658 * Property "impl.prefix" will be prepended to the classname 1659 * of the implementation object we instantiate, to which we 1660 * delegate the real work (like native methods). This 1661 * property can vary across implementations of the java. 1662 * classes. The default is an empty String "". 1663 */ 1664 String prefix = GetPropertyAction.privilegedGetProperty("impl.prefix", ""); 1665 try { 1666 @SuppressWarnings("deprecation") 1667 Object tmp = Class.forName("java.net." + prefix + implName).newInstance(); 1668 impl = tmp; 1669 } catch (ClassNotFoundException e) { 1670 System.err.println("Class not found: java.net." + prefix + 1671 implName + ":\ncheck impl.prefix property " + 1672 "in your properties file."); 1673 } catch (InstantiationException e) { 1674 System.err.println("Could not instantiate: java.net." + prefix + 1675 implName + ":\ncheck impl.prefix property " + 1676 "in your properties file."); 1677 } catch (IllegalAccessException e) { 1678 System.err.println("Cannot access class: java.net." + prefix + 1679 implName + ":\ncheck impl.prefix property " + 1680 "in your properties file."); 1681 } 1682 1683 if (impl == null) { 1684 try { 1685 @SuppressWarnings("deprecation") 1686 Object tmp = Class.forName(implName).newInstance(); 1687 impl = tmp; 1688 } catch (Exception e) { 1689 throw new Error("System property impl.prefix incorrect"); 1690 } 1691 } 1692 1693 return (InetAddressImpl) impl; 1694 } 1695 1696 private void readObjectNoData () { 1697 if (getClass().getClassLoader() != null) { 1698 throw new SecurityException ("invalid address type"); 1699 } 1700 } 1701 1702 private static final jdk.internal.misc.Unsafe UNSAFE 1703 = jdk.internal.misc.Unsafe.getUnsafe(); 1704 private static final long FIELDS_OFFSET 1705 = UNSAFE.objectFieldOffset(InetAddress.class, "holder"); 1706 1707 private void readObject (ObjectInputStream s) throws 1708 IOException, ClassNotFoundException { 1709 if (getClass().getClassLoader() != null) { 1710 throw new SecurityException ("invalid address type"); 1711 } 1712 GetField gf = s.readFields(); 1713 String host = (String)gf.get("hostName", null); 1714 int address = gf.get("address", 0); 1715 int family = gf.get("family", 0); 1716 if (family != IPv4 && family != IPv6) { 1717 throw new InvalidObjectException("invalid address family type: " + family); 1718 } 1719 InetAddressHolder h = new InetAddressHolder(host, address, family); 1720 UNSAFE.putReference(this, FIELDS_OFFSET, h); 1721 } 1722 1723 /* needed because the serializable fields no longer exist */ 1724 1725 /** 1726 * @serialField hostName String 1727 * @serialField address int 1728 * @serialField family int 1729 */ 1730 private static final ObjectStreamField[] serialPersistentFields = { 1731 new ObjectStreamField("hostName", String.class), 1732 new ObjectStreamField("address", int.class), 1733 new ObjectStreamField("family", int.class), 1734 }; 1735 1736 private void writeObject (ObjectOutputStream s) throws 1737 IOException { 1738 if (getClass().getClassLoader() != null) { 1739 throw new SecurityException ("invalid address type"); 1740 } 1741 PutField pf = s.putFields(); 1742 pf.put("hostName", holder().getHostName()); 1743 pf.put("address", holder().getAddress()); 1744 pf.put("family", holder().getFamily()); 1745 s.writeFields(); 1746 } 1747 } 1748 1749 /* 1750 * Simple factory to create the impl 1751 */ 1752 class InetAddressImplFactory { 1753 1754 static InetAddressImpl create() { 1755 return InetAddress.loadImpl(isIPv6Supported() ? 1756 "Inet6AddressImpl" : "Inet4AddressImpl"); 1757 } 1758 1759 static native boolean isIPv6Supported(); 1760 }