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