1 /*
   2  * Copyright (c) 1995, 2020, 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 
  49 import jdk.internal.access.JavaNetInetAddressAccess;
  50 import jdk.internal.access.SharedSecrets;
  51 import sun.security.action.*;
  52 import sun.net.InetAddressCachePolicy;
  53 import sun.net.util.IPAddressUtil;
  54 import sun.nio.cs.UTF_8;
  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 class InetAddress implements java.io.Serializable {
 200 
 201     @Native static final int PREFER_IPV4_VALUE = 0;
 202     @Native static final int PREFER_IPV6_VALUE = 1;
 203     @Native static final int PREFER_SYSTEM_VALUE = 2;
 204 
 205     /**
 206      * Specify the address family: Internet Protocol, Version 4
 207      * @since 1.4
 208      */
 209     @Native static final int IPv4 = 1;
 210 
 211     /**
 212      * Specify the address family: Internet Protocol, Version 6
 213      * @since 1.4
 214      */
 215     @Native static final int IPv6 = 2;
 216 
 217     /* Specify address family preference */
 218     static transient final int preferIPv6Address;
 219 
 220     static class InetAddressHolder {
 221         /**
 222          * Reserve the original application specified hostname.
 223          *
 224          * The original hostname is useful for domain-based endpoint
 225          * identification (see RFC 2818 and RFC 6125).  If an address
 226          * was created with a raw IP address, a reverse name lookup
 227          * may introduce endpoint identification security issue via
 228          * DNS forging.
 229          *
 230          * Oracle JSSE provider is using this original hostname, via
 231          * jdk.internal.misc.JavaNetAccess, for SSL/TLS endpoint identification.
 232          *
 233          * Note: May define a new public method in the future if necessary.
 234          */
 235         String originalHostName;
 236 
 237         InetAddressHolder() {}
 238 
 239         InetAddressHolder(String hostName, int address, int family) {
 240             this.originalHostName = hostName;
 241             this.hostName = hostName;
 242             this.address = address;
 243             this.family = family;
 244         }
 245 
 246         void init(String hostName, int family) {
 247             this.originalHostName = hostName;
 248             this.hostName = hostName;
 249             if (family != -1) {
 250                 this.family = family;
 251             }
 252         }
 253 
 254         String hostName;
 255 
 256         String getHostName() {
 257             return hostName;
 258         }
 259 
 260         String getOriginalHostName() {
 261             return originalHostName;
 262         }
 263 
 264         /**
 265          * Holds a 32-bit IPv4 address.
 266          */
 267         int address;
 268 
 269         int getAddress() {
 270             return address;
 271         }
 272 
 273         /**
 274          * Specifies the address family type, for instance, '1' for IPv4
 275          * addresses, and '2' for IPv6 addresses.
 276          */
 277         int family;
 278 
 279         int getFamily() {
 280             return family;
 281         }
 282     }
 283 
 284     /* Used to store the serializable fields of InetAddress */
 285     final transient InetAddressHolder holder;
 286 
 287     InetAddressHolder holder() {
 288         return holder;
 289     }
 290 
 291     /* Used to store the name service provider */
 292     private static transient NameService nameService;
 293 
 294     /**
 295      * Used to store the best available hostname.
 296      * Lazily initialized via a data race; safe because Strings are immutable.
 297      */
 298     private transient String canonicalHostName = null;
 299 
 300     /** use serialVersionUID from JDK 1.0.2 for interoperability */
 301     @java.io.Serial
 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.loader.BootLoader.loadLibrary("net");
 321         SharedSecrets.setJavaNetInetAddressAccess(
 322                 new JavaNetInetAddressAccess() {
 323                     public String getOriginalHostName(InetAddress ia) {
 324                         return ia.holder.getOriginalHostName();
 325                     }
 326 
 327                     public InetAddress getByName(String hostName,
 328                                                  InetAddress hostAddress)
 329                         throws UnknownHostException
 330                     {
 331                         return InetAddress.getByName(hostName, hostAddress);
 332                     }
 333 
 334                     public Inet4Address getByAddress(int address) {
 335                         return new Inet4Address(null, address);
 336                     }
 337 
 338                     public InetAddress getByAddress(byte[] addr,
 339                                                     int scope_id) {
 340                         assert addr.length == Inet6Address.INADDRSZ;
 341                         if (IPAddressUtil.isIPv4MappedAddress(addr)) {
 342                             assert scope_id == 0;
 343                             return getByAddress(IPAddressUtil.intFromIPv4MappedAddress(addr));
 344                         } else {
 345                             return new Inet6Address(addr, scope_id);
 346                         }
 347                     }
 348 
 349                     public int addressValue(Inet4Address inet4Address) {
 350                         return inet4Address.addressValue();
 351                     }
 352 
 353                     public byte[] addressBytes(Inet6Address inet6Address) {
 354                         return inet6Address.addressBytes();
 355                     }
 356                 }
 357         );
 358         init();
 359     }
 360 
 361     /**
 362      * Constructor for the Socket.accept() method.
 363      * This creates an empty InetAddress, which is filled in by
 364      * the accept() method.  This InetAddress, however, is not
 365      * put in the address cache, since it is not created by name.
 366      */
 367     InetAddress() {
 368         holder = new InetAddressHolder();
 369     }
 370 
 371     /**
 372      * Replaces the de-serialized object with an Inet4Address object.
 373      *
 374      * @return the alternate object to the de-serialized object.
 375      *
 376      * @throws ObjectStreamException if a new object replacing this
 377      * object could not be created
 378      */
 379     @java.io.Serial
 380     private Object readResolve() throws ObjectStreamException {
 381         // will replace the deserialized 'this' object
 382         return new Inet4Address(holder().getHostName(), holder().getAddress());
 383     }
 384 
 385     /**
 386      * Utility routine to check if the InetAddress is an
 387      * IP multicast address.
 388      * @return a {@code boolean} indicating if the InetAddress is
 389      * an IP multicast address
 390      * @since   1.1
 391      */
 392     public boolean isMulticastAddress() {
 393         return false;
 394     }
 395 
 396     /**
 397      * Utility routine to check if the InetAddress is a wildcard address.
 398      * @return a {@code boolean} indicating if the InetAddress is
 399      *         a wildcard address.
 400      * @since 1.4
 401      */
 402     public boolean isAnyLocalAddress() {
 403         return false;
 404     }
 405 
 406     /**
 407      * Utility routine to check if the InetAddress is a loopback address.
 408      *
 409      * @return a {@code boolean} indicating if the InetAddress is
 410      * a loopback address; or false otherwise.
 411      * @since 1.4
 412      */
 413     public boolean isLoopbackAddress() {
 414         return false;
 415     }
 416 
 417     /**
 418      * Utility routine to check if the InetAddress is an link local address.
 419      *
 420      * @return a {@code boolean} indicating if the InetAddress is
 421      * a link local address; or false if address is not a link local unicast address.
 422      * @since 1.4
 423      */
 424     public boolean isLinkLocalAddress() {
 425         return false;
 426     }
 427 
 428     /**
 429      * Utility routine to check if the InetAddress is a site local address.
 430      *
 431      * @return a {@code boolean} indicating if the InetAddress is
 432      * a site local address; or false if address is not a site local unicast address.
 433      * @since 1.4
 434      */
 435     public boolean isSiteLocalAddress() {
 436         return false;
 437     }
 438 
 439     /**
 440      * Utility routine to check if the multicast address has global scope.
 441      *
 442      * @return a {@code boolean} indicating if the address has
 443      *         is a multicast address of global scope, false if it is not
 444      *         of global scope or it is not a multicast address
 445      * @since 1.4
 446      */
 447     public boolean isMCGlobal() {
 448         return false;
 449     }
 450 
 451     /**
 452      * Utility routine to check if the multicast address has node scope.
 453      *
 454      * @return a {@code boolean} indicating if the address has
 455      *         is a multicast address of node-local scope, false if it is not
 456      *         of node-local scope or it is not a multicast address
 457      * @since 1.4
 458      */
 459     public boolean isMCNodeLocal() {
 460         return false;
 461     }
 462 
 463     /**
 464      * Utility routine to check if the multicast address has link scope.
 465      *
 466      * @return a {@code boolean} indicating if the address has
 467      *         is a multicast address of link-local scope, false if it is not
 468      *         of link-local scope or it is not a multicast address
 469      * @since 1.4
 470      */
 471     public boolean isMCLinkLocal() {
 472         return false;
 473     }
 474 
 475     /**
 476      * Utility routine to check if the multicast address has site scope.
 477      *
 478      * @return a {@code boolean} indicating if the address has
 479      *         is a multicast address of site-local scope, false if it is not
 480      *         of site-local scope or it is not a multicast address
 481      * @since 1.4
 482      */
 483     public boolean isMCSiteLocal() {
 484         return false;
 485     }
 486 
 487     /**
 488      * Utility routine to check if the multicast address has organization scope.
 489      *
 490      * @return a {@code boolean} indicating if the address has
 491      *         is a multicast address of organization-local scope,
 492      *         false if it is not of organization-local scope
 493      *         or it is not a multicast address
 494      * @since 1.4
 495      */
 496     public boolean isMCOrgLocal() {
 497         return false;
 498     }
 499 
 500 
 501     /**
 502      * Test whether that address is reachable. Best effort is made by the
 503      * implementation to try to reach the host, but firewalls and server
 504      * configuration may block requests resulting in a unreachable status
 505      * while some specific ports may be accessible.
 506      * A typical implementation will use ICMP ECHO REQUESTs if the
 507      * privilege can be obtained, otherwise it will try to establish
 508      * a TCP connection on port 7 (Echo) of the destination host.
 509      * <p>
 510      * The timeout value, in milliseconds, indicates the maximum amount of time
 511      * the try should take. If the operation times out before getting an
 512      * answer, the host is deemed unreachable. A negative value will result
 513      * in an IllegalArgumentException being thrown.
 514      *
 515      * @param   timeout the time, in milliseconds, before the call aborts
 516      * @return a {@code boolean} indicating if the address is reachable.
 517      * @throws IOException if a network error occurs
 518      * @throws  IllegalArgumentException if {@code timeout} is negative.
 519      * @since 1.5
 520      */
 521     public boolean isReachable(int timeout) throws IOException {
 522         return isReachable(null, 0 , timeout);
 523     }
 524 
 525     /**
 526      * Test whether that address is reachable. Best effort is made by the
 527      * implementation to try to reach the host, but firewalls and server
 528      * configuration may block requests resulting in a unreachable status
 529      * while some specific ports may be accessible.
 530      * A typical implementation will use ICMP ECHO REQUESTs if the
 531      * privilege can be obtained, otherwise it will try to establish
 532      * a TCP connection on port 7 (Echo) of the destination host.
 533      * <p>
 534      * The {@code network interface} and {@code ttl} parameters
 535      * let the caller specify which network interface the test will go through
 536      * and the maximum number of hops the packets should go through.
 537      * A negative value for the {@code ttl} will result in an
 538      * IllegalArgumentException being thrown.
 539      * <p>
 540      * The timeout value, in milliseconds, indicates the maximum amount of time
 541      * the try should take. If the operation times out before getting an
 542      * answer, the host is deemed unreachable. A negative value will result
 543      * in an IllegalArgumentException being thrown.
 544      *
 545      * @param   netif   the NetworkInterface through which the
 546      *                    test will be done, or null for any interface
 547      * @param   ttl     the maximum numbers of hops to try or 0 for the
 548      *                  default
 549      * @param   timeout the time, in milliseconds, before the call aborts
 550      * @throws  IllegalArgumentException if either {@code timeout}
 551      *                          or {@code ttl} are negative.
 552      * @return a {@code boolean} indicating if the address is reachable.
 553      * @throws IOException if a network error occurs
 554      * @since 1.5
 555      */
 556     public boolean isReachable(NetworkInterface netif, int ttl,
 557                                int timeout) throws IOException {
 558         if (ttl < 0)
 559             throw new IllegalArgumentException("ttl can't be negative");
 560         if (timeout < 0)
 561             throw new IllegalArgumentException("timeout can't be negative");
 562 
 563         return impl.isReachable(this, timeout, netif, ttl);
 564     }
 565 
 566     /**
 567      * Gets the host name for this IP address.
 568      *
 569      * <p>If this InetAddress was created with a host name,
 570      * this host name will be remembered and returned;
 571      * otherwise, a reverse name lookup will be performed
 572      * and the result will be returned based on the system
 573      * configured name lookup service. If a lookup of the name service
 574      * is required, call
 575      * {@link #getCanonicalHostName() getCanonicalHostName}.
 576      *
 577      * <p>If there is a security manager, its
 578      * {@code checkConnect} method is first called
 579      * with the hostname and {@code -1}
 580      * as its arguments to see if the operation is allowed.
 581      * If the operation is not allowed, it will return
 582      * the textual representation of the IP address.
 583      *
 584      * @return  the host name for this IP address, or if the operation
 585      *    is not allowed by the security check, the textual
 586      *    representation of the IP address.
 587      *
 588      * @see InetAddress#getCanonicalHostName
 589      * @see SecurityManager#checkConnect
 590      */
 591     public String getHostName() {
 592         return getHostName(true);
 593     }
 594 
 595     /**
 596      * Returns the hostname for this address.
 597      * If the host is equal to null, then this address refers to any
 598      * of the local machine's available network addresses.
 599      * this is package private so SocketPermission can make calls into
 600      * here without a security check.
 601      *
 602      * <p>If there is a security manager, this method first
 603      * calls its {@code checkConnect} method
 604      * with the hostname and {@code -1}
 605      * as its arguments to see if the calling code is allowed to know
 606      * the hostname for this IP address, i.e., to connect to the host.
 607      * If the operation is not allowed, it will return
 608      * the textual representation of the IP address.
 609      *
 610      * @return  the host name for this IP address, or if the operation
 611      *    is not allowed by the security check, the textual
 612      *    representation of the IP address.
 613      *
 614      * @param check make security check if true
 615      *
 616      * @see SecurityManager#checkConnect
 617      */
 618     String getHostName(boolean check) {
 619         if (holder().getHostName() == null) {
 620             holder().hostName = InetAddress.getHostFromNameService(this, check);
 621         }
 622         return holder().getHostName();
 623     }
 624 
 625     /**
 626      * Gets the fully qualified domain name for this IP address.
 627      * Best effort method, meaning we may not be able to return
 628      * the FQDN depending on the underlying system configuration.
 629      *
 630      * <p>If there is a security manager, this method first
 631      * calls its {@code checkConnect} method
 632      * with the hostname and {@code -1}
 633      * as its arguments to see if the calling code is allowed to know
 634      * the hostname for this IP address, i.e., to connect to the host.
 635      * If the operation is not allowed, it will return
 636      * the textual representation of the IP address.
 637      *
 638      * @return  the fully qualified domain name for this IP address,
 639      *    or if the operation is not allowed by the security check,
 640      *    the textual representation of the IP address.
 641      *
 642      * @see SecurityManager#checkConnect
 643      *
 644      * @since 1.4
 645      */
 646     public String getCanonicalHostName() {
 647         String value = canonicalHostName;
 648         if (value == null)
 649             canonicalHostName = value =
 650                 InetAddress.getHostFromNameService(this, true);
 651         return value;
 652     }
 653 
 654     /**
 655      * Returns the hostname for this address.
 656      *
 657      * <p>If there is a security manager, this method first
 658      * calls its {@code checkConnect} method
 659      * with the hostname and {@code -1}
 660      * as its arguments to see if the calling code is allowed to know
 661      * the hostname for this IP address, i.e., to connect to the host.
 662      * If the operation is not allowed, it will return
 663      * the textual representation of the IP address.
 664      *
 665      * @return  the host name for this IP address, or if the operation
 666      *    is not allowed by the security check, the textual
 667      *    representation of the IP address.
 668      *
 669      * @param check make security check if true
 670      *
 671      * @see SecurityManager#checkConnect
 672      */
 673     private static String getHostFromNameService(InetAddress addr, boolean check) {
 674         String host = null;
 675             try {
 676                 // first lookup the hostname
 677                 host = nameService.getHostByAddr(addr.getAddress());
 678 
 679                 /* check to see if calling code is allowed to know
 680                  * the hostname for this IP address, ie, connect to the host
 681                  */
 682                 if (check) {
 683                     SecurityManager sec = System.getSecurityManager();
 684                     if (sec != null) {
 685                         sec.checkConnect(host, -1);
 686                     }
 687                 }
 688 
 689                 /* now get all the IP addresses for this hostname,
 690                  * and make sure one of them matches the original IP
 691                  * address. We do this to try and prevent spoofing.
 692                  */
 693 
 694                 InetAddress[] arr = InetAddress.getAllByName0(host, check);
 695                 boolean ok = false;
 696 
 697                 if(arr != null) {
 698                     for(int i = 0; !ok && i < arr.length; i++) {
 699                         ok = addr.equals(arr[i]);
 700                     }
 701                 }
 702 
 703                 //XXX: if it looks a spoof just return the address?
 704                 if (!ok) {
 705                     host = addr.getHostAddress();
 706                     return host;
 707                 }
 708             } catch (SecurityException e) {
 709                 host = addr.getHostAddress();
 710             } catch (UnknownHostException e) {
 711                 host = addr.getHostAddress();
 712                 // let next provider resolve the hostname
 713             }
 714         return host;
 715     }
 716 
 717     /**
 718      * Returns the raw IP address of this {@code InetAddress}
 719      * object. The result is in network byte order: the highest order
 720      * byte of the address is in {@code getAddress()[0]}.
 721      *
 722      * @return  the raw IP address of this object.
 723      */
 724     public byte[] getAddress() {
 725         return null;
 726     }
 727 
 728     /**
 729      * Returns the IP address string in textual presentation.
 730      *
 731      * @return  the raw IP address in a string format.
 732      * @since   1.0.2
 733      */
 734     public String getHostAddress() {
 735         return null;
 736      }
 737 
 738     /**
 739      * Returns a hashcode for this IP address.
 740      *
 741      * @return  a hash code value for this IP address.
 742      */
 743     public int hashCode() {
 744         return -1;
 745     }
 746 
 747     /**
 748      * Compares this object against the specified object.
 749      * The result is {@code true} if and only if the argument is
 750      * not {@code null} and it represents the same IP address as
 751      * this object.
 752      * <p>
 753      * Two instances of {@code InetAddress} represent the same IP
 754      * address if the length of the byte arrays returned by
 755      * {@code getAddress} is the same for both, and each of the
 756      * array components is the same for the byte arrays.
 757      *
 758      * @param   obj   the object to compare against.
 759      * @return  {@code true} if the objects are the same;
 760      *          {@code false} otherwise.
 761      * @see     java.net.InetAddress#getAddress()
 762      */
 763     public boolean equals(Object obj) {
 764         return false;
 765     }
 766 
 767     /**
 768      * Converts this IP address to a {@code String}. The
 769      * string returned is of the form: hostname / literal IP
 770      * address.
 771      *
 772      * If the host name is unresolved, no reverse name service lookup
 773      * is performed. The hostname part will be represented by an empty string.
 774      *
 775      * @return  a string representation of this IP address.
 776      */
 777     public String toString() {
 778         String hostName = holder().getHostName();
 779         return Objects.toString(hostName, "")
 780             + "/" + getHostAddress();
 781     }
 782 
 783     // mapping from host name to Addresses - either NameServiceAddresses (while
 784     // still being looked-up by NameService(s)) or CachedAddresses when cached
 785     private static final ConcurrentMap<String, Addresses> cache =
 786         new ConcurrentHashMap<>();
 787 
 788     // CachedAddresses that have to expire are kept ordered in this NavigableSet
 789     // which is scanned on each access
 790     private static final NavigableSet<CachedAddresses> expirySet =
 791         new ConcurrentSkipListSet<>();
 792 
 793     // common interface
 794     private interface Addresses {
 795         InetAddress[] get() throws UnknownHostException;
 796     }
 797 
 798     // a holder for cached addresses with required metadata
 799     private static final class CachedAddresses  implements Addresses, Comparable<CachedAddresses> {
 800         private static final AtomicLong seq = new AtomicLong();
 801         final String host;
 802         final InetAddress[] inetAddresses;
 803         final long expiryTime; // time of expiry (in terms of System.nanoTime())
 804         final long id = seq.incrementAndGet(); // each instance is unique
 805 
 806         CachedAddresses(String host, InetAddress[] inetAddresses, long expiryTime) {
 807             this.host = host;
 808             this.inetAddresses = inetAddresses;
 809             this.expiryTime = expiryTime;
 810         }
 811 
 812         @Override
 813         public InetAddress[] get() throws UnknownHostException {
 814             if (inetAddresses == null) {
 815                 throw new UnknownHostException(host);
 816             }
 817             return inetAddresses;
 818         }
 819 
 820         @Override
 821         public int compareTo(CachedAddresses other) {
 822             // natural order is expiry time -
 823             // compare difference of expiry times rather than
 824             // expiry times directly, to avoid possible overflow.
 825             // (see System.nanoTime() recommendations...)
 826             long diff = this.expiryTime - other.expiryTime;
 827             if (diff < 0L) return -1;
 828             if (diff > 0L) return 1;
 829             // ties are broken using unique id
 830             return Long.compare(this.id, other.id);
 831         }
 832     }
 833 
 834     // a name service lookup based Addresses implementation which replaces itself
 835     // in cache when the result is obtained
 836     private static final class NameServiceAddresses implements Addresses {
 837         private final String host;
 838         private final InetAddress reqAddr;
 839 
 840         NameServiceAddresses(String host, InetAddress reqAddr) {
 841             this.host = host;
 842             this.reqAddr = reqAddr;
 843         }
 844 
 845         @Override
 846         public InetAddress[] get() throws UnknownHostException {
 847             Addresses addresses;
 848             // only one thread is doing lookup to name service
 849             // for particular host at any time.
 850             synchronized (this) {
 851                 // re-check that we are still us + re-install us if slot empty
 852                 addresses = cache.putIfAbsent(host, this);
 853                 if (addresses == null) {
 854                     // this can happen when we were replaced by CachedAddresses in
 855                     // some other thread, then CachedAddresses expired and were
 856                     // removed from cache while we were waiting for lock...
 857                     addresses = this;
 858                 }
 859                 // still us ?
 860                 if (addresses == this) {
 861                     // lookup name services
 862                     InetAddress[] inetAddresses;
 863                     UnknownHostException ex;
 864                     int cachePolicy;
 865                     try {
 866                         inetAddresses = getAddressesFromNameService(host, reqAddr);
 867                         ex = null;
 868                         cachePolicy = InetAddressCachePolicy.get();
 869                     } catch (UnknownHostException uhe) {
 870                         inetAddresses = null;
 871                         ex = uhe;
 872                         cachePolicy = InetAddressCachePolicy.getNegative();
 873                     }
 874                     // remove or replace us with cached addresses according to cachePolicy
 875                     if (cachePolicy == InetAddressCachePolicy.NEVER) {
 876                         cache.remove(host, this);
 877                     } else {
 878                         CachedAddresses cachedAddresses = new CachedAddresses(
 879                             host,
 880                             inetAddresses,
 881                             cachePolicy == InetAddressCachePolicy.FOREVER
 882                             ? 0L
 883                             // cachePolicy is in [s] - we need [ns]
 884                             : System.nanoTime() + 1000_000_000L * cachePolicy
 885                         );
 886                         if (cache.replace(host, this, cachedAddresses) &&
 887                             cachePolicy != InetAddressCachePolicy.FOREVER) {
 888                             // schedule expiry
 889                             expirySet.add(cachedAddresses);
 890                         }
 891                     }
 892                     if (inetAddresses == null) {
 893                         throw ex == null ? new UnknownHostException(host) : ex;
 894                     }
 895                     return inetAddresses;
 896                 }
 897                 // else addresses != this
 898             }
 899             // delegate to different addresses when we are already replaced
 900             // but outside of synchronized block to avoid any chance of dead-locking
 901             return addresses.get();
 902         }
 903     }
 904 
 905     /**
 906      * NameService provides host and address lookup service
 907      *
 908      * @since 9
 909      */
 910     private interface NameService {
 911 
 912         /**
 913          * Lookup a host mapping by name. Retrieve the IP addresses
 914          * associated with a host
 915          *
 916          * @param host the specified hostname
 917          * @return array of IP addresses for the requested host
 918          * @throws UnknownHostException
 919          *             if no IP address for the {@code host} could be found
 920          */
 921         InetAddress[] lookupAllHostAddr(String host)
 922                 throws UnknownHostException;
 923 
 924         /**
 925          * Lookup the host corresponding to the IP address provided
 926          *
 927          * @param addr byte array representing an IP address
 928          * @return {@code String} representing the host name mapping
 929          * @throws UnknownHostException
 930          *             if no host found for the specified IP address
 931          */
 932         String getHostByAddr(byte[] addr) throws UnknownHostException;
 933 
 934     }
 935 
 936     /**
 937      * The default NameService implementation, which delegates to the underlying
 938      * OS network libraries to resolve host address mappings.
 939      *
 940      * @since 9
 941      */
 942     private static final class PlatformNameService implements NameService {
 943 
 944         public InetAddress[] lookupAllHostAddr(String host)
 945             throws UnknownHostException
 946         {
 947             return impl.lookupAllHostAddr(host);
 948         }
 949 
 950         public String getHostByAddr(byte[] addr)
 951             throws UnknownHostException
 952         {
 953             return impl.getHostByAddr(addr);
 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             SecurityManager security = System.getSecurityManager();
1469             if (security != null) {
1470                 security.checkConnect(host, -1);
1471             }
1472         }
1473 
1474         // remove expired addresses from cache - expirySet keeps them ordered
1475         // by expiry time so we only need to iterate the prefix of the NavigableSet...
1476         long now = System.nanoTime();
1477         for (CachedAddresses caddrs : expirySet) {
1478             // compare difference of time instants rather than
1479             // time instants directly, to avoid possible overflow.
1480             // (see System.nanoTime() recommendations...)
1481             if ((caddrs.expiryTime - now) < 0L) {
1482                 // ConcurrentSkipListSet uses weakly consistent iterator,
1483                 // so removing while iterating is OK...
1484                 if (expirySet.remove(caddrs)) {
1485                     // ... remove from cache
1486                     cache.remove(caddrs.host, caddrs);
1487                 }
1488             } else {
1489                 // we encountered 1st element that expires in future
1490                 break;
1491             }
1492         }
1493 
1494         // look-up or remove from cache
1495         Addresses addrs;
1496         if (useCache) {
1497             addrs = cache.get(host);
1498         } else {
1499             addrs = cache.remove(host);
1500             if (addrs != null) {
1501                 if (addrs instanceof CachedAddresses) {
1502                     // try removing from expirySet too if CachedAddresses
1503                     expirySet.remove(addrs);
1504                 }
1505                 addrs = null;
1506             }
1507         }
1508 
1509         if (addrs == null) {
1510             // create a NameServiceAddresses instance which will look up
1511             // the name service and install it within cache...
1512             Addresses oldAddrs = cache.putIfAbsent(
1513                 host,
1514                 addrs = new NameServiceAddresses(host, reqAddr)
1515             );
1516             if (oldAddrs != null) { // lost putIfAbsent race
1517                 addrs = oldAddrs;
1518             }
1519         }
1520 
1521         // ask Addresses to get an array of InetAddress(es) and clone it
1522         return addrs.get().clone();
1523     }
1524 
1525     static InetAddress[] getAddressesFromNameService(String host, InetAddress reqAddr)
1526         throws UnknownHostException
1527     {
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                 }
1537                 else {
1538                     ex = uhe;
1539                 }
1540             }
1541 
1542         if (addresses == null) {
1543             throw ex == null ? new UnknownHostException(host) : ex;
1544         }
1545 
1546         // More to do?
1547         if (reqAddr != null && addresses.length > 1 && !addresses[0].equals(reqAddr)) {
1548             // Find it?
1549             int i = 1;
1550             for (; i < addresses.length; i++) {
1551                 if (addresses[i].equals(reqAddr)) {
1552                     break;
1553                 }
1554             }
1555             // Rotate
1556             if (i < addresses.length) {
1557                 InetAddress tmp, tmp2 = reqAddr;
1558                 for (int j = 0; j < i; j++) {
1559                     tmp = addresses[j];
1560                     addresses[j] = tmp2;
1561                     tmp2 = tmp;
1562                 }
1563                 addresses[i] = tmp2;
1564             }
1565         }
1566 
1567         return addresses;
1568     }
1569 
1570     /**
1571      * Returns an {@code InetAddress} object given the raw IP address .
1572      * The argument is in network byte order: the highest order
1573      * byte of the address is in {@code getAddress()[0]}.
1574      *
1575      * <p> This method doesn't block, i.e. no reverse name service lookup
1576      * is performed.
1577      *
1578      * <p> IPv4 address byte array must be 4 bytes long and IPv6 byte array
1579      * must be 16 bytes long
1580      *
1581      * @param addr the raw IP address in network byte order
1582      * @return  an InetAddress object created from the raw IP address.
1583      * @throws     UnknownHostException  if IP address is of illegal length
1584      * @since 1.4
1585      */
1586     public static InetAddress getByAddress(byte[] addr)
1587         throws UnknownHostException {
1588         return getByAddress(null, addr);
1589     }
1590 
1591     private static final class CachedLocalHost {
1592         final String host;
1593         final InetAddress addr;
1594         final long expiryTime = System.nanoTime() + 5000_000_000L; // now + 5s;
1595 
1596         CachedLocalHost(String host, InetAddress addr) {
1597             this.host = host;
1598             this.addr = addr;
1599         }
1600     }
1601 
1602     private static volatile CachedLocalHost cachedLocalHost;
1603 
1604     /**
1605      * Returns the address of the local host. This is achieved by retrieving
1606      * the name of the host from the system, then resolving that name into
1607      * an {@code InetAddress}.
1608      *
1609      * <P>Note: The resolved address may be cached for a short period of time.
1610      * </P>
1611      *
1612      * <p>If there is a security manager, its
1613      * {@code checkConnect} method is called
1614      * with the local host name and {@code -1}
1615      * as its arguments to see if the operation is allowed.
1616      * If the operation is not allowed, an InetAddress representing
1617      * the loopback address is returned.
1618      *
1619      * @return     the address of the local host.
1620      *
1621      * @throws     UnknownHostException  if the local host name could not
1622      *             be resolved into an address.
1623      *
1624      * @see SecurityManager#checkConnect
1625      * @see java.net.InetAddress#getByName(java.lang.String)
1626      */
1627     public static InetAddress getLocalHost() throws UnknownHostException {
1628 
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      * Load and instantiate an underlying impl class
1687      */
1688     static InetAddressImpl loadImpl(String implName) {
1689         Object impl = null;
1690 
1691         /*
1692          * Property "impl.prefix" will be prepended to the classname
1693          * of the implementation object we instantiate, to which we
1694          * delegate the real work (like native methods).  This
1695          * property can vary across implementations of the java.
1696          * classes.  The default is an empty String "".
1697          */
1698         String prefix = GetPropertyAction.privilegedGetProperty("impl.prefix", "");
1699         try {
1700             @SuppressWarnings("deprecation")
1701             Object tmp = Class.forName("java.net." + prefix + implName).newInstance();
1702             impl = tmp;
1703         } catch (ClassNotFoundException e) {
1704             System.err.println("Class not found: java.net." + prefix +
1705                                implName + ":\ncheck impl.prefix property " +
1706                                "in your properties file.");
1707         } catch (InstantiationException e) {
1708             System.err.println("Could not instantiate: java.net." + prefix +
1709                                implName + ":\ncheck impl.prefix property " +
1710                                "in your properties file.");
1711         } catch (IllegalAccessException e) {
1712             System.err.println("Cannot access class: java.net." + prefix +
1713                                implName + ":\ncheck impl.prefix property " +
1714                                "in your properties file.");
1715         }
1716 
1717         if (impl == null) {
1718             try {
1719                 @SuppressWarnings("deprecation")
1720                 Object tmp = Class.forName(implName).newInstance();
1721                 impl = tmp;
1722             } catch (Exception e) {
1723                 throw new Error("System property impl.prefix incorrect");
1724             }
1725         }
1726 
1727         return (InetAddressImpl) impl;
1728     }
1729 
1730     @java.io.Serial
1731     private void readObjectNoData () {
1732         if (getClass().getClassLoader() != null) {
1733             throw new SecurityException ("invalid address type");
1734         }
1735     }
1736 
1737     private static final jdk.internal.misc.Unsafe UNSAFE
1738             = jdk.internal.misc.Unsafe.getUnsafe();
1739     private static final long FIELDS_OFFSET
1740             = UNSAFE.objectFieldOffset(InetAddress.class, "holder");
1741 
1742     @java.io.Serial
1743     private void readObject (ObjectInputStream s) throws
1744                          IOException, ClassNotFoundException {
1745         if (getClass().getClassLoader() != null) {
1746             throw new SecurityException ("invalid address type");
1747         }
1748         GetField gf = s.readFields();
1749         String host = (String)gf.get("hostName", null);
1750         int address = gf.get("address", 0);
1751         int family = gf.get("family", 0);
1752         if (family != IPv4 && family != IPv6) {
1753             throw new InvalidObjectException("invalid address family type: " + family);
1754         }
1755         InetAddressHolder h = new InetAddressHolder(host, address, family);
1756         UNSAFE.putReference(this, FIELDS_OFFSET, h);
1757     }
1758 
1759     /* needed because the serializable fields no longer exist */
1760 
1761     /**
1762      * @serialField hostName String
1763      * @serialField address int
1764      * @serialField family int
1765      */
1766     @java.io.Serial
1767     private static final ObjectStreamField[] serialPersistentFields = {
1768         new ObjectStreamField("hostName", String.class),
1769         new ObjectStreamField("address", int.class),
1770         new ObjectStreamField("family", int.class),
1771     };
1772 
1773     @java.io.Serial
1774     private void writeObject (ObjectOutputStream s) throws
1775                         IOException {
1776         if (getClass().getClassLoader() != null) {
1777             throw new SecurityException ("invalid address type");
1778         }
1779         PutField pf = s.putFields();
1780         pf.put("hostName", holder().getHostName());
1781         pf.put("address", holder().getAddress());
1782         pf.put("family", holder().getFamily());
1783         s.writeFields();
1784     }
1785 }
1786 
1787 /*
1788  * Simple factory to create the impl
1789  */
1790 class InetAddressImplFactory {
1791 
1792     static InetAddressImpl create() {
1793         return InetAddress.loadImpl(isIPv6Supported() ?
1794                                     "Inet6AddressImpl" : "Inet4AddressImpl");
1795     }
1796 
1797     static native boolean isIPv6Supported();
1798 }