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