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()
 321                 .loadLibrary(InetAddress.class, "net");
 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         String value = canonicalHostName;
 625         if (value == null)
 626             canonicalHostName = value =
 627                 InetAddress.getHostFromNameService(this, true);
 628         return value;
 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             try (Scanner hostsFileScanner = new Scanner(new File(hostsFile), "UTF-8")) {
 988                 while (hostsFileScanner.hasNextLine()) {
 989                     hostEntry = hostsFileScanner.nextLine();
 990                     if (!hostEntry.startsWith("#")) {
 991                         hostEntry = removeComments(hostEntry);
 992                         String[] mapping = hostEntry.split("\\s+");
 993                         if (mapping.length >= 2 &&
 994                             Arrays.equals(addr, createAddressByteArray(mapping[0]))) {
 995                             host = mapping[1];
 996                             break;
 997                         }
 998                     }
 999                 }
1000             } catch (FileNotFoundException e) {
1001                 throw new UnknownHostException("Unable to resolve address "
1002                         + Arrays.toString(addr) + " as hosts file " + hostsFile
1003                         + " not found ");
1004             }
1005 
1006             if ((host == null) || (host.isEmpty()) || (host.equals(" "))) {
1007                 throw new UnknownHostException("Requested address "
1008                         + Arrays.toString(addr)
1009                         + " resolves to an invalid entry in hosts file "
1010                         + hostsFile);
1011             }
1012             return host;
1013         }
1014 
1015         /**
1016          * <p>Lookup a host mapping by name. Retrieve the IP addresses
1017          * associated with a host.
1018          *
1019          * <p>Search the configured hosts file for the addresses associated
1020          * with the specified host name.
1021          *
1022          * @param host the specified hostname
1023          * @return array of IP addresses for the requested host
1024          * @throws UnknownHostException
1025          *             if no IP address for the {@code host} could be found
1026          */
1027         public InetAddress[] lookupAllHostAddr(String host)
1028                 throws UnknownHostException {
1029             String hostEntry;
1030             String addrStr = null;
1031             InetAddress[] res = null;
1032             byte addr[] = new byte[4];
1033             ArrayList<InetAddress> inetAddresses = null;
1034 
1035             // lookup the file and create a list InetAddress for the specified host
1036             try (Scanner hostsFileScanner = new Scanner(new File(hostsFile), "UTF-8")) {
1037                 while (hostsFileScanner.hasNextLine()) {
1038                     hostEntry = hostsFileScanner.nextLine();
1039                     if (!hostEntry.startsWith("#")) {
1040                         hostEntry = removeComments(hostEntry);
1041                         if (hostEntry.contains(host)) {
1042                             addrStr = extractHostAddr(hostEntry, host);
1043                             if ((addrStr != null) && (!addrStr.isEmpty())) {
1044                                 addr = createAddressByteArray(addrStr);
1045                                 if (inetAddresses == null) {
1046                                     inetAddresses = new ArrayList<>(1);
1047                                 }
1048                                 if (addr != null) {
1049                                     inetAddresses.add(InetAddress.getByAddress(host, addr));
1050                                 }
1051                             }
1052                         }
1053                     }
1054                 }
1055             } catch (FileNotFoundException e) {
1056                 throw new UnknownHostException("Unable to resolve host " + host
1057                         + " as hosts file " + hostsFile + " not found ");
1058             }
1059 
1060             if (inetAddresses != null) {
1061                 res = inetAddresses.toArray(new InetAddress[inetAddresses.size()]);
1062             } else {
1063                 throw new UnknownHostException("Unable to resolve host " + host
1064                         + " in hosts file " + hostsFile);
1065             }
1066             return res;
1067         }
1068 
1069         private String removeComments(String hostsEntry) {
1070             String filteredEntry = hostsEntry;
1071             int hashIndex;
1072 
1073             if ((hashIndex = hostsEntry.indexOf("#")) != -1) {
1074                 filteredEntry = hostsEntry.substring(0, hashIndex);
1075             }
1076             return filteredEntry;
1077         }
1078 
1079         private byte [] createAddressByteArray(String addrStr) {
1080             byte[] addrArray;
1081             // check if IPV4 address - most likely
1082             addrArray = IPAddressUtil.textToNumericFormatV4(addrStr);
1083             if (addrArray == null) {
1084                 addrArray = IPAddressUtil.textToNumericFormatV6(addrStr);
1085             }
1086             return addrArray;
1087         }
1088 
1089         /** host to ip address mapping */
1090         private String extractHostAddr(String hostEntry, String host) {
1091             String[] mapping = hostEntry.split("\\s+");
1092             String hostAddr = null;
1093 
1094             if (mapping.length >= 2) {
1095                 // look at the host aliases
1096                 for (int i = 1; i < mapping.length; i++) {
1097                     if (mapping[i].equalsIgnoreCase(host)) {
1098                         hostAddr = mapping[0];
1099                     }
1100                 }
1101             }
1102             return hostAddr;
1103         }
1104     }
1105 
1106     static final InetAddressImpl  impl;
1107 
1108     static {
1109         // create the impl
1110         impl = InetAddressImplFactory.create();
1111 
1112         // create name service
1113         nameService = createNameService();
1114         }
1115 
1116     /**
1117      * Create an instance of the NameService interface based on
1118      * the setting of the {@code jdk.net.hosts.file} system property.
1119      *
1120      * <p>The default NameService is the PlatformNameService, which typically
1121      * delegates name and address resolution calls to the underlying
1122      * OS network libraries.
1123      *
1124      * <p> A HostsFileNameService is created if the {@code jdk.net.hosts.file}
1125      * system property is set. If the specified file doesn't exist, the name or
1126      * address lookup will result in an UnknownHostException. Thus, non existent
1127      * hosts file is handled as if the file is empty.
1128      *
1129      * @return a NameService
1130      */
1131     private static NameService createNameService() {
1132 
1133         String hostsFileName =
1134                 GetPropertyAction.privilegedGetProperty("jdk.net.hosts.file");
1135         NameService theNameService;
1136         if (hostsFileName != null) {
1137             theNameService = new HostsFileNameService(hostsFileName);
1138         } else {
1139             theNameService = new PlatformNameService();
1140         }
1141         return theNameService;
1142     }
1143 
1144     /**
1145      * Creates an InetAddress based on the provided host name and IP address.
1146      * No name service is checked for the validity of the address.
1147      *
1148      * <p> The host name can either be a machine name, such as
1149      * "{@code www.example.com}", or a textual representation of its IP
1150      * address.
1151      * <p> No validity checking is done on the host name either.
1152      *
1153      * <p> If addr specifies an IPv4 address an instance of Inet4Address
1154      * will be returned; otherwise, an instance of Inet6Address
1155      * will be returned.
1156      *
1157      * <p> IPv4 address byte array must be 4 bytes long and IPv6 byte array
1158      * must be 16 bytes long
1159      *
1160      * @param host the specified host
1161      * @param addr the raw IP address in network byte order
1162      * @return  an InetAddress object created from the raw IP address.
1163      * @exception  UnknownHostException  if IP address is of illegal length
1164      * @since 1.4
1165      */
1166     public static InetAddress getByAddress(String host, byte[] addr)
1167         throws UnknownHostException {
1168         if (host != null && !host.isEmpty() && host.charAt(0) == '[') {
1169             if (host.charAt(host.length()-1) == ']') {
1170                 host = host.substring(1, host.length() -1);
1171             }
1172         }
1173         if (addr != null) {
1174             if (addr.length == Inet4Address.INADDRSZ) {
1175                 return new Inet4Address(host, addr);
1176             } else if (addr.length == Inet6Address.INADDRSZ) {
1177                 byte[] newAddr
1178                     = IPAddressUtil.convertFromIPv4MappedAddress(addr);
1179                 if (newAddr != null) {
1180                     return new Inet4Address(host, newAddr);
1181                 } else {
1182                     return new Inet6Address(host, addr);
1183                 }
1184             }
1185         }
1186         throw new UnknownHostException("addr is of illegal length");
1187     }
1188 
1189 
1190     /**
1191      * Determines the IP address of a host, given the host's name.
1192      *
1193      * <p> The host name can either be a machine name, such as
1194      * "{@code www.example.com}", or a textual representation of its
1195      * IP address. If a literal IP address is supplied, only the
1196      * validity of the address format is checked.
1197      *
1198      * <p> For {@code host} specified in literal IPv6 address,
1199      * either the form defined in RFC 2732 or the literal IPv6 address
1200      * format defined in RFC 2373 is accepted. IPv6 scoped addresses are also
1201      * supported. See <a href="Inet6Address.html#scoped">here</a> for a description of IPv6
1202      * scoped addresses.
1203      *
1204      * <p> If the host is {@code null} or {@code host.length()} is equal
1205      * to zero, then an {@code InetAddress} representing an address of the
1206      * loopback interface is returned.
1207      * See <a href="http://www.ietf.org/rfc/rfc3330.txt">RFC&nbsp;3330</a>
1208      * section&nbsp;2 and <a href="http://www.ietf.org/rfc/rfc2373.txt">RFC&nbsp;2373</a>
1209      * section&nbsp;2.5.3.
1210      *
1211      * <p> If there is a security manager, and {@code host} is not {@code null}
1212      * or {@code host.length() } is not equal to zero, the security manager's
1213      * {@code checkConnect} method is called with the hostname and {@code -1}
1214      * as its arguments to determine if the operation is allowed.
1215      *
1216      * @param      host   the specified host, or {@code null}.
1217      * @return     an IP address for the given host name.
1218      * @exception  UnknownHostException  if no IP address for the
1219      *               {@code host} could be found, or if a scope_id was specified
1220      *               for a global IPv6 address.
1221      * @exception  SecurityException if a security manager exists
1222      *             and its checkConnect method doesn't allow the operation
1223      */
1224     public static InetAddress getByName(String host)
1225         throws UnknownHostException {
1226         return InetAddress.getAllByName(host)[0];
1227     }
1228 
1229     // called from deployment cache manager
1230     private static InetAddress getByName(String host, InetAddress reqAddr)
1231         throws UnknownHostException {
1232         return InetAddress.getAllByName(host, reqAddr)[0];
1233     }
1234 
1235     /**
1236      * Given the name of a host, returns an array of its IP addresses,
1237      * based on the configured name service on the system.
1238      *
1239      * <p> The host name can either be a machine name, such as
1240      * "{@code www.example.com}", or a textual representation of its IP
1241      * address. If a literal IP address is supplied, only the
1242      * validity of the address format is checked.
1243      *
1244      * <p> For {@code host} specified in <i>literal IPv6 address</i>,
1245      * either the form defined in RFC 2732 or the literal IPv6 address
1246      * format defined in RFC 2373 is accepted. A literal IPv6 address may
1247      * also be qualified by appending a scoped zone identifier or scope_id.
1248      * The syntax and usage of scope_ids is described
1249      * <a href="Inet6Address.html#scoped">here</a>.
1250      *
1251      * <p> If the host is {@code null} or {@code host.length()} is equal
1252      * to zero, then an {@code InetAddress} representing an address of the
1253      * loopback interface is returned.
1254      * See <a href="http://www.ietf.org/rfc/rfc3330.txt">RFC&nbsp;3330</a>
1255      * section&nbsp;2 and <a href="http://www.ietf.org/rfc/rfc2373.txt">RFC&nbsp;2373</a>
1256      * section&nbsp;2.5.3. </p>
1257      *
1258      * <p> If there is a security manager, and {@code host} is not {@code null}
1259      * or {@code host.length() } is not equal to zero, the security manager's
1260      * {@code checkConnect} method is called with the hostname and {@code -1}
1261      * as its arguments to determine if the operation is allowed.
1262      *
1263      * @param      host   the name of the host, or {@code null}.
1264      * @return     an array of all the IP addresses for a given host name.
1265      *
1266      * @exception  UnknownHostException  if no IP address for the
1267      *               {@code host} could be found, or if a scope_id was specified
1268      *               for a global IPv6 address.
1269      * @exception  SecurityException  if a security manager exists and its
1270      *               {@code checkConnect} method doesn't allow the operation.
1271      *
1272      * @see SecurityManager#checkConnect
1273      */
1274     public static InetAddress[] getAllByName(String host)
1275         throws UnknownHostException {
1276         return getAllByName(host, null);
1277     }
1278 
1279     private static InetAddress[] getAllByName(String host, InetAddress reqAddr)
1280         throws UnknownHostException {
1281 
1282         if (host == null || host.isEmpty()) {
1283             InetAddress[] ret = new InetAddress[1];
1284             ret[0] = impl.loopbackAddress();
1285             return ret;
1286         }
1287 
1288         boolean ipv6Expected = false;
1289         if (host.charAt(0) == '[') {
1290             // This is supposed to be an IPv6 literal
1291             if (host.length() > 2 && host.charAt(host.length()-1) == ']') {
1292                 host = host.substring(1, host.length() -1);
1293                 ipv6Expected = true;
1294             } else {
1295                 // This was supposed to be a IPv6 address, but it's not!
1296                 throw new UnknownHostException(host + ": invalid IPv6 address");
1297             }
1298         }
1299 
1300         // if host is an IP address, we won't do further lookup
1301         if (Character.digit(host.charAt(0), 16) != -1
1302             || (host.charAt(0) == ':')) {
1303             byte[] addr = null;
1304             int numericZone = -1;
1305             String ifname = null;
1306             // see if it is IPv4 address
1307             addr = IPAddressUtil.textToNumericFormatV4(host);
1308             if (addr == null) {
1309                 // This is supposed to be an IPv6 literal
1310                 // Check if a numeric or string zone id is present
1311                 int pos;
1312                 if ((pos=host.indexOf ('%')) != -1) {
1313                     numericZone = checkNumericZone (host);
1314                     if (numericZone == -1) { /* remainder of string must be an ifname */
1315                         ifname = host.substring (pos+1);
1316                     }
1317                 }
1318                 if ((addr = IPAddressUtil.textToNumericFormatV6(host)) == null && host.contains(":")) {
1319                     throw new UnknownHostException(host + ": invalid IPv6 address");
1320                 }
1321             } else if (ipv6Expected) {
1322                 // Means an IPv4 literal between brackets!
1323                 throw new UnknownHostException("["+host+"]");
1324             }
1325             InetAddress[] ret = new InetAddress[1];
1326             if(addr != null) {
1327                 if (addr.length == Inet4Address.INADDRSZ) {
1328                     ret[0] = new Inet4Address(null, addr);
1329                 } else {
1330                     if (ifname != null) {
1331                         ret[0] = new Inet6Address(null, addr, ifname);
1332                     } else {
1333                         ret[0] = new Inet6Address(null, addr, numericZone);
1334                     }
1335                 }
1336                 return ret;
1337             }
1338         } else if (ipv6Expected) {
1339             // We were expecting an IPv6 Literal, but got something else
1340             throw new UnknownHostException("["+host+"]");
1341         }
1342         return getAllByName0(host, reqAddr, true, true);
1343     }
1344 
1345     /**
1346      * Returns the loopback address.
1347      * <p>
1348      * The InetAddress returned will represent the IPv4
1349      * loopback address, 127.0.0.1, or the IPv6 loopback
1350      * address, ::1. The IPv4 loopback address returned
1351      * is only one of many in the form 127.*.*.*
1352      *
1353      * @return  the InetAddress loopback instance.
1354      * @since 1.7
1355      */
1356     public static InetAddress getLoopbackAddress() {
1357         return impl.loopbackAddress();
1358     }
1359 
1360 
1361     /**
1362      * check if the literal address string has %nn appended
1363      * returns -1 if not, or the numeric value otherwise.
1364      *
1365      * %nn may also be a string that represents the displayName of
1366      * a currently available NetworkInterface.
1367      */
1368     private static int checkNumericZone (String s) throws UnknownHostException {
1369         int percent = s.indexOf ('%');
1370         int slen = s.length();
1371         int digit, zone=0;
1372         if (percent == -1) {
1373             return -1;
1374         }
1375         for (int i=percent+1; i<slen; i++) {
1376             char c = s.charAt(i);
1377             if (c == ']') {
1378                 if (i == percent+1) {
1379                     /* empty per-cent field */
1380                     return -1;
1381                 }
1382                 break;
1383             }
1384             if ((digit = Character.digit (c, 10)) < 0) {
1385                 return -1;
1386             }
1387             zone = (zone * 10) + digit;
1388         }
1389         return zone;
1390     }
1391 
1392     private static InetAddress[] getAllByName0 (String host)
1393         throws UnknownHostException
1394     {
1395         return getAllByName0(host, true);
1396     }
1397 
1398     /**
1399      * package private so SocketPermission can call it
1400      */
1401     static InetAddress[] getAllByName0 (String host, boolean check)
1402         throws UnknownHostException  {
1403         return getAllByName0 (host, null, check, true);
1404     }
1405 
1406     /**
1407      * Designated lookup method.
1408      *
1409      * @param host host name to look up
1410      * @param reqAddr requested address to be the 1st in returned array
1411      * @param check perform security check
1412      * @param useCache use cached value if not expired else always
1413      *                 perform name service lookup (and cache the result)
1414      * @return array of InetAddress(es)
1415      * @throws UnknownHostException if host name is not found
1416      */
1417     private static InetAddress[] getAllByName0(String host,
1418                                                InetAddress reqAddr,
1419                                                boolean check,
1420                                                boolean useCache)
1421         throws UnknownHostException  {
1422 
1423         /* If it gets here it is presumed to be a hostname */
1424 
1425         /* make sure the connection to the host is allowed, before we
1426          * give out a hostname
1427          */
1428         if (check) {
1429             SecurityManager security = System.getSecurityManager();
1430             if (security != null) {
1431                 security.checkConnect(host, -1);
1432             }
1433         }
1434 
1435         // remove expired addresses from cache - expirySet keeps them ordered
1436         // by expiry time so we only need to iterate the prefix of the NavigableSet...
1437         long now = System.nanoTime();
1438         for (CachedAddresses caddrs : expirySet) {
1439             // compare difference of time instants rather than
1440             // time instants directly, to avoid possible overflow.
1441             // (see System.nanoTime() recommendations...)
1442             if ((caddrs.expiryTime - now) < 0L) {
1443                 // ConcurrentSkipListSet uses weakly consistent iterator,
1444                 // so removing while iterating is OK...
1445                 if (expirySet.remove(caddrs)) {
1446                     // ... remove from cache
1447                     cache.remove(caddrs.host, caddrs);
1448                 }
1449             } else {
1450                 // we encountered 1st element that expires in future
1451                 break;
1452             }
1453         }
1454 
1455         // look-up or remove from cache
1456         Addresses addrs;
1457         if (useCache) {
1458             addrs = cache.get(host);
1459         } else {
1460             addrs = cache.remove(host);
1461             if (addrs != null) {
1462                 if (addrs instanceof CachedAddresses) {
1463                     // try removing from expirySet too if CachedAddresses
1464                     expirySet.remove(addrs);
1465                 }
1466                 addrs = null;
1467             }
1468         }
1469 
1470         if (addrs == null) {
1471             // create a NameServiceAddresses instance which will look up
1472             // the name service and install it within cache...
1473             Addresses oldAddrs = cache.putIfAbsent(
1474                 host,
1475                 addrs = new NameServiceAddresses(host, reqAddr)
1476             );
1477             if (oldAddrs != null) { // lost putIfAbsent race
1478                 addrs = oldAddrs;
1479             }
1480         }
1481 
1482         // ask Addresses to get an array of InetAddress(es) and clone it
1483         return addrs.get().clone();
1484     }
1485 
1486     static InetAddress[] getAddressesFromNameService(String host, InetAddress reqAddr)
1487         throws UnknownHostException
1488     {
1489         InetAddress[] addresses = null;
1490         UnknownHostException ex = null;
1491 
1492             try {
1493                 addresses = nameService.lookupAllHostAddr(host);
1494             } catch (UnknownHostException uhe) {
1495                 if (host.equalsIgnoreCase("localhost")) {
1496                     addresses = new InetAddress[] { impl.loopbackAddress() };
1497                 }
1498                 else {
1499                     ex = uhe;
1500                 }
1501             }
1502 
1503         if (addresses == null) {
1504             throw ex == null ? new UnknownHostException(host) : ex;
1505         }
1506 
1507         // More to do?
1508         if (reqAddr != null && addresses.length > 1 && !addresses[0].equals(reqAddr)) {
1509             // Find it?
1510             int i = 1;
1511             for (; i < addresses.length; i++) {
1512                 if (addresses[i].equals(reqAddr)) {
1513                     break;
1514                 }
1515             }
1516             // Rotate
1517             if (i < addresses.length) {
1518                 InetAddress tmp, tmp2 = reqAddr;
1519                 for (int j = 0; j < i; j++) {
1520                     tmp = addresses[j];
1521                     addresses[j] = tmp2;
1522                     tmp2 = tmp;
1523                 }
1524                 addresses[i] = tmp2;
1525             }
1526         }
1527 
1528         return addresses;
1529     }
1530 
1531     /**
1532      * Returns an {@code InetAddress} object given the raw IP address .
1533      * The argument is in network byte order: the highest order
1534      * byte of the address is in {@code getAddress()[0]}.
1535      *
1536      * <p> This method doesn't block, i.e. no reverse name service lookup
1537      * is performed.
1538      *
1539      * <p> IPv4 address byte array must be 4 bytes long and IPv6 byte array
1540      * must be 16 bytes long
1541      *
1542      * @param addr the raw IP address in network byte order
1543      * @return  an InetAddress object created from the raw IP address.
1544      * @exception  UnknownHostException  if IP address is of illegal length
1545      * @since 1.4
1546      */
1547     public static InetAddress getByAddress(byte[] addr)
1548         throws UnknownHostException {
1549         return getByAddress(null, addr);
1550     }
1551 
1552     private static final class CachedLocalHost {
1553         final String host;
1554         final InetAddress addr;
1555         final long expiryTime = System.nanoTime() + 5000_000_000L; // now + 5s;
1556 
1557         CachedLocalHost(String host, InetAddress addr) {
1558             this.host = host;
1559             this.addr = addr;
1560         }
1561     }
1562 
1563     private static volatile CachedLocalHost cachedLocalHost;
1564 
1565     /**
1566      * Returns the address of the local host. This is achieved by retrieving
1567      * the name of the host from the system, then resolving that name into
1568      * an {@code InetAddress}.
1569      *
1570      * <P>Note: The resolved address may be cached for a short period of time.
1571      * </P>
1572      *
1573      * <p>If there is a security manager, its
1574      * {@code checkConnect} method is called
1575      * with the local host name and {@code -1}
1576      * as its arguments to see if the operation is allowed.
1577      * If the operation is not allowed, an InetAddress representing
1578      * the loopback address is returned.
1579      *
1580      * @return     the address of the local host.
1581      *
1582      * @exception  UnknownHostException  if the local host name could not
1583      *             be resolved into an address.
1584      *
1585      * @see SecurityManager#checkConnect
1586      * @see java.net.InetAddress#getByName(java.lang.String)
1587      */
1588     public static InetAddress getLocalHost() throws UnknownHostException {
1589 
1590         SecurityManager security = System.getSecurityManager();
1591         try {
1592             // is cached data still valid?
1593             CachedLocalHost clh = cachedLocalHost;
1594             if (clh != null && (clh.expiryTime - System.nanoTime()) >= 0L) {
1595                 if (security != null) {
1596                     security.checkConnect(clh.host, -1);
1597                 }
1598                 return clh.addr;
1599             }
1600 
1601             String local = impl.getLocalHostName();
1602 
1603             if (security != null) {
1604                 security.checkConnect(local, -1);
1605             }
1606 
1607             InetAddress localAddr;
1608             if (local.equals("localhost")) {
1609                 // shortcut for "localhost" host name
1610                 localAddr = impl.loopbackAddress();
1611             } else {
1612                 // call getAllByName0 without security checks and
1613                 // without using cached data
1614                 try {
1615                     localAddr = getAllByName0(local, null, false, false)[0];
1616                 } catch (UnknownHostException uhe) {
1617                     // Rethrow with a more informative error message.
1618                     UnknownHostException uhe2 =
1619                         new UnknownHostException(local + ": " +
1620                                                  uhe.getMessage());
1621                     uhe2.initCause(uhe);
1622                     throw uhe2;
1623                 }
1624             }
1625             cachedLocalHost = new CachedLocalHost(local, localAddr);
1626             return localAddr;
1627         } catch (java.lang.SecurityException e) {
1628             return impl.loopbackAddress();
1629         }
1630     }
1631 
1632     /**
1633      * Perform class load-time initializations.
1634      */
1635     private static native void init();
1636 
1637 
1638     /*
1639      * Returns the InetAddress representing anyLocalAddress
1640      * (typically 0.0.0.0 or ::0)
1641      */
1642     static InetAddress anyLocalAddress() {
1643         return impl.anyLocalAddress();
1644     }
1645 
1646     /*
1647      * Load and instantiate an underlying impl class
1648      */
1649     static InetAddressImpl loadImpl(String implName) {
1650         Object impl = null;
1651 
1652         /*
1653          * Property "impl.prefix" will be prepended to the classname
1654          * of the implementation object we instantiate, to which we
1655          * delegate the real work (like native methods).  This
1656          * property can vary across implementations of the java.
1657          * classes.  The default is an empty String "".
1658          */
1659         String prefix = GetPropertyAction.privilegedGetProperty("impl.prefix", "");
1660         try {
1661             @SuppressWarnings("deprecation")
1662             Object tmp = Class.forName("java.net." + prefix + implName).newInstance();
1663             impl = tmp;
1664         } catch (ClassNotFoundException e) {
1665             System.err.println("Class not found: java.net." + prefix +
1666                                implName + ":\ncheck impl.prefix property " +
1667                                "in your properties file.");
1668         } catch (InstantiationException e) {
1669             System.err.println("Could not instantiate: java.net." + prefix +
1670                                implName + ":\ncheck impl.prefix property " +
1671                                "in your properties file.");
1672         } catch (IllegalAccessException e) {
1673             System.err.println("Cannot access class: java.net." + prefix +
1674                                implName + ":\ncheck impl.prefix property " +
1675                                "in your properties file.");
1676         }
1677 
1678         if (impl == null) {
1679             try {
1680                 @SuppressWarnings("deprecation")
1681                 Object tmp = Class.forName(implName).newInstance();
1682                 impl = tmp;
1683             } catch (Exception e) {
1684                 throw new Error("System property impl.prefix incorrect");
1685             }
1686         }
1687 
1688         return (InetAddressImpl) impl;
1689     }
1690 
1691     private void readObjectNoData () {
1692         if (getClass().getClassLoader() != null) {
1693             throw new SecurityException ("invalid address type");
1694         }
1695     }
1696 
1697     private static final jdk.internal.misc.Unsafe UNSAFE
1698             = jdk.internal.misc.Unsafe.getUnsafe();
1699     private static final long FIELDS_OFFSET
1700             = UNSAFE.objectFieldOffset(InetAddress.class, "holder");
1701 
1702     private void readObject (ObjectInputStream s) throws
1703                          IOException, ClassNotFoundException {
1704         if (getClass().getClassLoader() != null) {
1705             throw new SecurityException ("invalid address type");
1706         }
1707         GetField gf = s.readFields();
1708         String host = (String)gf.get("hostName", null);
1709         int address = gf.get("address", 0);
1710         int family = gf.get("family", 0);
1711         if (family != IPv4 && family != IPv6) {
1712             throw new InvalidObjectException("invalid address family type: " + family);
1713         }
1714         InetAddressHolder h = new InetAddressHolder(host, address, family);
1715         UNSAFE.putReference(this, FIELDS_OFFSET, h);
1716     }
1717 
1718     /* needed because the serializable fields no longer exist */
1719 
1720     /**
1721      * @serialField hostName String
1722      * @serialField address int
1723      * @serialField family int
1724      */
1725     private static final ObjectStreamField[] serialPersistentFields = {
1726         new ObjectStreamField("hostName", String.class),
1727         new ObjectStreamField("address", int.class),
1728         new ObjectStreamField("family", int.class),
1729     };
1730 
1731     private void writeObject (ObjectOutputStream s) throws
1732                         IOException {
1733         if (getClass().getClassLoader() != null) {
1734             throw new SecurityException ("invalid address type");
1735         }
1736         PutField pf = s.putFields();
1737         pf.put("hostName", holder().getHostName());
1738         pf.put("address", holder().getAddress());
1739         pf.put("family", holder().getFamily());
1740         s.writeFields();
1741     }
1742 }
1743 
1744 /*
1745  * Simple factory to create the impl
1746  */
1747 class InetAddressImplFactory {
1748 
1749     static InetAddressImpl create() {
1750         return InetAddress.loadImpl(isIPv6Supported() ?
1751                                     "Inet6AddressImpl" : "Inet4AddressImpl");
1752     }
1753 
1754     static native boolean isIPv6Supported();
1755 }