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