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