1 /*
   2  * Copyright (c) 1995, 2011, 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.HashMap;
  29 import java.util.LinkedHashMap;
  30 import java.util.Random;
  31 import java.util.Iterator;
  32 import java.util.LinkedList;
  33 import java.util.List;
  34 import java.util.ArrayList;
  35 import java.util.ServiceLoader;
  36 import java.security.AccessController;
  37 import java.io.ObjectStreamException;
  38 import java.io.IOException;
  39 import java.io.ObjectInputStream;
  40 import sun.security.action.*;
  41 import sun.net.InetAddressCachePolicy;
  42 import sun.net.util.IPAddressUtil;
  43 import sun.net.spi.nameservice.*;
  44 
  45 /**
  46  * This class represents an Internet Protocol (IP) address.
  47  *
  48  * <p> An IP address is either a 32-bit or 128-bit unsigned number
  49  * used by IP, a lower-level protocol on which protocols like UDP and
  50  * TCP are built. The IP address architecture is defined by <a
  51  * href="http://www.ietf.org/rfc/rfc790.txt"><i>RFC&nbsp;790:
  52  * Assigned Numbers</i></a>, <a
  53  * href="http://www.ietf.org/rfc/rfc1918.txt"> <i>RFC&nbsp;1918:
  54  * Address Allocation for Private Internets</i></a>, <a
  55  * href="http://www.ietf.org/rfc/rfc2365.txt"><i>RFC&nbsp;2365:
  56  * Administratively Scoped IP Multicast</i></a>, and <a
  57  * href="http://www.ietf.org/rfc/rfc2373.txt"><i>RFC&nbsp;2373: IP
  58  * Version 6 Addressing Architecture</i></a>. An instance of an
  59  * InetAddress consists of an IP address and possibly its
  60  * corresponding host name (depending on whether it is constructed
  61  * with a host name or whether it has already done reverse host name
  62  * resolution).
  63  *
  64  * <h4> Address types </h4>
  65  *
  66  * <blockquote><table cellspacing=2 summary="Description of unicast and multicast address types">
  67  *   <tr><th valign=top><i>unicast</i></th>
  68  *       <td>An identifier for a single interface. A packet sent to
  69  *         a unicast address is delivered to the interface identified by
  70  *         that address.
  71  *
  72  *         <p> The Unspecified Address -- Also called anylocal or wildcard
  73  *         address. It must never be assigned to any node. It indicates the
  74  *         absence of an address. One example of its use is as the target of
  75  *         bind, which allows a server to accept a client connection on any
  76  *         interface, in case the server host has multiple interfaces.
  77  *
  78  *         <p> The <i>unspecified</i> address must not be used as
  79  *         the destination address of an IP packet.
  80  *
  81  *         <p> The <i>Loopback</i> Addresses -- This is the address
  82  *         assigned to the loopback interface. Anything sent to this
  83  *         IP address loops around and becomes IP input on the local
  84  *         host. This address is often used when testing a
  85  *         client.</td></tr>
  86  *   <tr><th valign=top><i>multicast</i></th>
  87  *       <td>An identifier for a set of interfaces (typically belonging
  88  *         to different nodes). A packet sent to a multicast address is
  89  *         delivered to all interfaces identified by that address.</td></tr>
  90  * </table></blockquote>
  91  *
  92  * <h4> IP address scope </h4>
  93  *
  94  * <p> <i>Link-local</i> addresses are designed to be used for addressing
  95  * on a single link for purposes such as auto-address configuration,
  96  * neighbor discovery, or when no routers are present.
  97  *
  98  * <p> <i>Site-local</i> addresses are designed to be used for addressing
  99  * inside of a site without the need for a global prefix.
 100  *
 101  * <p> <i>Global</i> addresses are unique across the internet.
 102  *
 103  * <h4> Textual representation of IP addresses </h4>
 104  *
 105  * The textual representation of an IP address is address family specific.
 106  *
 107  * <p>
 108  *
 109  * For IPv4 address format, please refer to <A
 110  * HREF="Inet4Address.html#format">Inet4Address#format</A>; For IPv6
 111  * address format, please refer to <A
 112  * HREF="Inet6Address.html#format">Inet6Address#format</A>.
 113  *
 114  * <P>There is a <a href="doc-files/net-properties.html#Ipv4IPv6">couple of
 115  * System Properties</a> affecting how IPv4 and IPv6 addresses are used.</P>
 116  *
 117  * <h4> Host Name Resolution </h4>
 118  *
 119  * Host name-to-IP address <i>resolution</i> is accomplished through
 120  * the use of a combination of local machine configuration information
 121  * and network naming services such as the Domain Name System (DNS)
 122  * and Network Information Service(NIS). The particular naming
 123  * services(s) being used is by default the local machine configured
 124  * one. For any host name, its corresponding IP address is returned.
 125  *
 126  * <p> <i>Reverse name resolution</i> means that for any IP address,
 127  * the host associated with the IP address is returned.
 128  *
 129  * <p> The InetAddress class provides methods to resolve host names to
 130  * their IP addresses and vice versa.
 131  *
 132  * <h4> InetAddress Caching </h4>
 133  *
 134  * The InetAddress class has a cache to store successful as well as
 135  * unsuccessful host name resolutions.
 136  *
 137  * <p> By default, when a security manager is installed, in order to
 138  * protect against DNS spoofing attacks,
 139  * the result of positive host name resolutions are
 140  * cached forever. When a security manager is not installed, the default
 141  * behavior is to cache entries for a finite (implementation dependent)
 142  * period of time. The result of unsuccessful host
 143  * name resolution is cached for a very short period of time (10
 144  * seconds) to improve performance.
 145  *
 146  * <p> If the default behavior is not desired, then a Java security property
 147  * can be set to a different Time-to-live (TTL) value for positive
 148  * caching. Likewise, a system admin can configure a different
 149  * negative caching TTL value when needed.
 150  *
 151  * <p> Two Java security properties control the TTL values used for
 152  *  positive and negative host name resolution caching:
 153  *
 154  * <blockquote>
 155  * <dl>
 156  * <dt><b>networkaddress.cache.ttl</b></dt>
 157  * <dd>Indicates the caching policy for successful name lookups from
 158  * the name service. The value is specified as as integer to indicate
 159  * the number of seconds to cache the successful lookup. The default
 160  * setting is to cache for an implementation specific period of time.
 161  * <p>
 162  * A value of -1 indicates "cache forever".
 163  * </dd>
 164  * <p>
 165  * <dt><b>networkaddress.cache.negative.ttl</b> (default: 10)</dt>
 166  * <dd>Indicates the caching policy for un-successful name lookups
 167  * from the name service. The value is specified as as integer to
 168  * indicate the number of seconds to cache the failure for
 169  * un-successful lookups.
 170  * <p>
 171  * A value of 0 indicates "never cache".
 172  * A value of -1 indicates "cache forever".
 173  * </dd>
 174  * </dl>
 175  * </blockquote>
 176  *
 177  * @author  Chris Warth
 178  * @see     java.net.InetAddress#getByAddress(byte[])
 179  * @see     java.net.InetAddress#getByAddress(java.lang.String, byte[])
 180  * @see     java.net.InetAddress#getAllByName(java.lang.String)
 181  * @see     java.net.InetAddress#getByName(java.lang.String)
 182  * @see     java.net.InetAddress#getLocalHost()
 183  * @since JDK1.0
 184  */
 185 public
 186 class InetAddress implements java.io.Serializable {
 187     /**
 188      * Specify the address family: Internet Protocol, Version 4
 189      * @since 1.4
 190      */
 191     static final int IPv4 = 1;
 192 
 193     /**
 194      * Specify the address family: Internet Protocol, Version 6
 195      * @since 1.4
 196      */
 197     static final int IPv6 = 2;
 198 
 199     /* Specify address family preference */
 200     static transient boolean preferIPv6Address = false;
 201 
 202     /**
 203      * @serial
 204      */
 205     String hostName;
 206 
 207     /**
 208      * Holds a 32-bit IPv4 address.
 209      *
 210      * @serial
 211      */
 212     int address;
 213 
 214     /**
 215      * Specifies the address family type, for instance, '1' for IPv4
 216      * addresses, and '2' for IPv6 addresses.
 217      *
 218      * @serial
 219      */
 220     int family;
 221 
 222     /* Used to store the name service provider */
 223     private static List<NameService> nameServices = null;
 224 
 225     /* Used to store the best available hostname */
 226     private transient String canonicalHostName = null;
 227 
 228     /** use serialVersionUID from JDK 1.0.2 for interoperability */
 229     private static final long serialVersionUID = 3286316764910316507L;
 230 
 231     /*
 232      * Load net library into runtime, and perform initializations.
 233      */
 234     static {
 235         preferIPv6Address = java.security.AccessController.doPrivileged(
 236             new GetBooleanAction("java.net.preferIPv6Addresses")).booleanValue();
 237         AccessController.doPrivileged(new LoadLibraryAction("net"));
 238         init();
 239     }
 240 
 241     /**
 242      * Constructor for the Socket.accept() method.
 243      * This creates an empty InetAddress, which is filled in by
 244      * the accept() method.  This InetAddress, however, is not
 245      * put in the address cache, since it is not created by name.
 246      */
 247     InetAddress() {
 248     }
 249 
 250     /**
 251      * Replaces the de-serialized object with an Inet4Address object.
 252      *
 253      * @return the alternate object to the de-serialized object.
 254      *
 255      * @throws ObjectStreamException if a new object replacing this
 256      * object could not be created
 257      */
 258     private Object readResolve() throws ObjectStreamException {
 259         // will replace the deserialized 'this' object
 260         return new Inet4Address(this.hostName, this.address);
 261     }
 262 
 263     /**
 264      * Utility routine to check if the InetAddress is an
 265      * IP multicast address.
 266      * @return a <code>boolean</code> indicating if the InetAddress is
 267      * an IP multicast address
 268      * @since   JDK1.1
 269      */
 270     public boolean isMulticastAddress() {
 271         return false;
 272     }
 273 
 274     /**
 275      * Utility routine to check if the InetAddress in a wildcard address.
 276      * @return a <code>boolean</code> indicating if the Inetaddress is
 277      *         a wildcard address.
 278      * @since 1.4
 279      */
 280     public boolean isAnyLocalAddress() {
 281         return false;
 282     }
 283 
 284     /**
 285      * Utility routine to check if the InetAddress is a loopback address.
 286      *
 287      * @return a <code>boolean</code> indicating if the InetAddress is
 288      * a loopback address; or false otherwise.
 289      * @since 1.4
 290      */
 291     public boolean isLoopbackAddress() {
 292         return false;
 293     }
 294 
 295     /**
 296      * Utility routine to check if the InetAddress is an link local address.
 297      *
 298      * @return a <code>boolean</code> indicating if the InetAddress is
 299      * a link local address; or false if address is not a link local unicast address.
 300      * @since 1.4
 301      */
 302     public boolean isLinkLocalAddress() {
 303         return false;
 304     }
 305 
 306     /**
 307      * Utility routine to check if the InetAddress is a site local address.
 308      *
 309      * @return a <code>boolean</code> indicating if the InetAddress is
 310      * a site local address; or false if address is not a site local unicast address.
 311      * @since 1.4
 312      */
 313     public boolean isSiteLocalAddress() {
 314         return false;
 315     }
 316 
 317     /**
 318      * Utility routine to check if the multicast address has global scope.
 319      *
 320      * @return a <code>boolean</code> indicating if the address has
 321      *         is a multicast address of global scope, false if it is not
 322      *         of global scope or it is not a multicast address
 323      * @since 1.4
 324      */
 325     public boolean isMCGlobal() {
 326         return false;
 327     }
 328 
 329     /**
 330      * Utility routine to check if the multicast address has node scope.
 331      *
 332      * @return a <code>boolean</code> indicating if the address has
 333      *         is a multicast address of node-local scope, false if it is not
 334      *         of node-local scope or it is not a multicast address
 335      * @since 1.4
 336      */
 337     public boolean isMCNodeLocal() {
 338         return false;
 339     }
 340 
 341     /**
 342      * Utility routine to check if the multicast address has link scope.
 343      *
 344      * @return a <code>boolean</code> indicating if the address has
 345      *         is a multicast address of link-local scope, false if it is not
 346      *         of link-local scope or it is not a multicast address
 347      * @since 1.4
 348      */
 349     public boolean isMCLinkLocal() {
 350         return false;
 351     }
 352 
 353     /**
 354      * Utility routine to check if the multicast address has site scope.
 355      *
 356      * @return a <code>boolean</code> indicating if the address has
 357      *         is a multicast address of site-local scope, false if it is not
 358      *         of site-local scope or it is not a multicast address
 359      * @since 1.4
 360      */
 361     public boolean isMCSiteLocal() {
 362         return false;
 363     }
 364 
 365     /**
 366      * Utility routine to check if the multicast address has organization scope.
 367      *
 368      * @return a <code>boolean</code> indicating if the address has
 369      *         is a multicast address of organization-local scope,
 370      *         false if it is not of organization-local scope
 371      *         or it is not a multicast address
 372      * @since 1.4
 373      */
 374     public boolean isMCOrgLocal() {
 375         return false;
 376     }
 377 
 378 
 379     /**
 380      * Test whether that address is reachable. Best effort is made by the
 381      * implementation to try to reach the host, but firewalls and server
 382      * configuration may block requests resulting in a unreachable status
 383      * while some specific ports may be accessible.
 384      * A typical implementation will use ICMP ECHO REQUESTs if the
 385      * privilege can be obtained, otherwise it will try to establish
 386      * a TCP connection on port 7 (Echo) of the destination host.
 387      * <p>
 388      * The timeout value, in milliseconds, indicates the maximum amount of time
 389      * the try should take. If the operation times out before getting an
 390      * answer, the host is deemed unreachable. A negative value will result
 391      * in an IllegalArgumentException being thrown.
 392      *
 393      * @param   timeout the time, in milliseconds, before the call aborts
 394      * @return a <code>boolean</code> indicating if the address is reachable.
 395      * @throws IOException if a network error occurs
 396      * @throws  IllegalArgumentException if <code>timeout</code> is negative.
 397      * @since 1.5
 398      */
 399     public boolean isReachable(int timeout) throws IOException {
 400         return isReachable(null, 0 , timeout);
 401     }
 402 
 403     /**
 404      * Test whether that address is reachable. Best effort is made by the
 405      * implementation to try to reach the host, but firewalls and server
 406      * configuration may block requests resulting in a unreachable status
 407      * while some specific ports may be accessible.
 408      * A typical implementation will use ICMP ECHO REQUESTs if the
 409      * privilege can be obtained, otherwise it will try to establish
 410      * a TCP connection on port 7 (Echo) of the destination host.
 411      * <p>
 412      * The <code>network interface</code> and <code>ttl</code> parameters
 413      * let the caller specify which network interface the test will go through
 414      * and the maximum number of hops the packets should go through.
 415      * A negative value for the <code>ttl</code> will result in an
 416      * IllegalArgumentException being thrown.
 417      * <p>
 418      * The timeout value, in milliseconds, indicates the maximum amount of time
 419      * the try should take. If the operation times out before getting an
 420      * answer, the host is deemed unreachable. A negative value will result
 421      * in an IllegalArgumentException being thrown.
 422      *
 423      * @param   netif   the NetworkInterface through which the
 424      *                    test will be done, or null for any interface
 425      * @param   ttl     the maximum numbers of hops to try or 0 for the
 426      *                  default
 427      * @param   timeout the time, in milliseconds, before the call aborts
 428      * @throws  IllegalArgumentException if either <code>timeout</code>
 429      *                          or <code>ttl</code> are negative.
 430      * @return a <code>boolean</code>indicating if the address is reachable.
 431      * @throws IOException if a network error occurs
 432      * @since 1.5
 433      */
 434     public boolean isReachable(NetworkInterface netif, int ttl,
 435                                int timeout) throws IOException {
 436         if (ttl < 0)
 437             throw new IllegalArgumentException("ttl can't be negative");
 438         if (timeout < 0)
 439             throw new IllegalArgumentException("timeout can't be negative");
 440 
 441         return impl.isReachable(this, timeout, netif, ttl);
 442     }
 443 
 444     /**
 445      * Gets the host name for this IP address.
 446      *
 447      * <p>If this InetAddress was created with a host name,
 448      * this host name will be remembered and returned;
 449      * otherwise, a reverse name lookup will be performed
 450      * and the result will be returned based on the system
 451      * configured name lookup service. If a lookup of the name service
 452      * is required, call
 453      * {@link #getCanonicalHostName() getCanonicalHostName}.
 454      *
 455      * <p>If there is a security manager, its
 456      * <code>checkConnect</code> method is first called
 457      * with the hostname and <code>-1</code>
 458      * as its arguments to see if the operation is allowed.
 459      * If the operation is not allowed, it will return
 460      * the textual representation of the IP address.
 461      *
 462      * @return  the host name for this IP address, or if the operation
 463      *    is not allowed by the security check, the textual
 464      *    representation of the IP address.
 465      *
 466      * @see InetAddress#getCanonicalHostName
 467      * @see SecurityManager#checkConnect
 468      */
 469     public String getHostName() {
 470         return getHostName(true);
 471     }
 472 
 473     /**
 474      * Returns the hostname for this address.
 475      * If the host is equal to null, then this address refers to any
 476      * of the local machine's available network addresses.
 477      * this is package private so SocketPermission can make calls into
 478      * here without a security check.
 479      *
 480      * <p>If there is a security manager, this method first
 481      * calls its <code>checkConnect</code> method
 482      * with the hostname and <code>-1</code>
 483      * as its arguments to see if the calling code is allowed to know
 484      * the hostname for this IP address, i.e., to connect to the host.
 485      * If the operation is not allowed, it will return
 486      * the textual representation of the IP address.
 487      *
 488      * @return  the host name for this IP address, or if the operation
 489      *    is not allowed by the security check, the textual
 490      *    representation of the IP address.
 491      *
 492      * @param check make security check if true
 493      *
 494      * @see SecurityManager#checkConnect
 495      */
 496     String getHostName(boolean check) {
 497         if (hostName == null) {
 498             hostName = InetAddress.getHostFromNameService(this, check);
 499         }
 500         return hostName;
 501     }
 502 
 503     /**
 504      * Gets the fully qualified domain name for this IP address.
 505      * Best effort method, meaning we may not be able to return
 506      * the FQDN depending on the underlying system configuration.
 507      *
 508      * <p>If there is a security manager, this method first
 509      * calls its <code>checkConnect</code> method
 510      * with the hostname and <code>-1</code>
 511      * as its arguments to see if the calling code is allowed to know
 512      * the hostname for this IP address, i.e., to connect to the host.
 513      * If the operation is not allowed, it will return
 514      * the textual representation of the IP address.
 515      *
 516      * @return  the fully qualified domain name for this IP address,
 517      *    or if the operation is not allowed by the security check,
 518      *    the textual representation of the IP address.
 519      *
 520      * @see SecurityManager#checkConnect
 521      *
 522      * @since 1.4
 523      */
 524     public String getCanonicalHostName() {
 525         if (canonicalHostName == null) {
 526             canonicalHostName =
 527                 InetAddress.getHostFromNameService(this, true);
 528         }
 529         return canonicalHostName;
 530     }
 531 
 532     /**
 533      * Returns the hostname for this address.
 534      *
 535      * <p>If there is a security manager, this method first
 536      * calls its <code>checkConnect</code> method
 537      * with the hostname and <code>-1</code>
 538      * as its arguments to see if the calling code is allowed to know
 539      * the hostname for this IP address, i.e., to connect to the host.
 540      * If the operation is not allowed, it will return
 541      * the textual representation of the IP address.
 542      *
 543      * @return  the host name for this IP address, or if the operation
 544      *    is not allowed by the security check, the textual
 545      *    representation of the IP address.
 546      *
 547      * @param check make security check if true
 548      *
 549      * @see SecurityManager#checkConnect
 550      */
 551     private static String getHostFromNameService(InetAddress addr, boolean check) {
 552         String host = null;
 553         for (NameService nameService : nameServices) {
 554             try {
 555                 // first lookup the hostname
 556                 host = nameService.getHostByAddr(addr.getAddress());
 557 
 558                 /* check to see if calling code is allowed to know
 559                  * the hostname for this IP address, ie, connect to the host
 560                  */
 561                 if (check) {
 562                     SecurityManager sec = System.getSecurityManager();
 563                     if (sec != null) {
 564                         sec.checkConnect(host, -1);
 565                     }
 566                 }
 567 
 568                 /* now get all the IP addresses for this hostname,
 569                  * and make sure one of them matches the original IP
 570                  * address. We do this to try and prevent spoofing.
 571                  */
 572 
 573                 InetAddress[] arr = InetAddress.getAllByName0(host, check);
 574                 boolean ok = false;
 575 
 576                 if(arr != null) {
 577                     for(int i = 0; !ok && i < arr.length; i++) {
 578                         ok = addr.equals(arr[i]);
 579                     }
 580                 }
 581 
 582                 //XXX: if it looks a spoof just return the address?
 583                 if (!ok) {
 584                     host = addr.getHostAddress();
 585                     return host;
 586                 }
 587 
 588                 break;
 589 
 590             } catch (SecurityException e) {
 591                 host = addr.getHostAddress();
 592                 break;
 593             } catch (UnknownHostException e) {
 594                 host = addr.getHostAddress();
 595                 // let next provider resolve the hostname
 596             }
 597         }
 598 
 599         return host;
 600     }
 601 
 602     /**
 603      * Returns the raw IP address of this <code>InetAddress</code>
 604      * object. The result is in network byte order: the highest order
 605      * byte of the address is in <code>getAddress()[0]</code>.
 606      *
 607      * @return  the raw IP address of this object.
 608      */
 609     public byte[] getAddress() {
 610         return null;
 611     }
 612 
 613     /**
 614      * Returns the IP address string in textual presentation.
 615      *
 616      * @return  the raw IP address in a string format.
 617      * @since   JDK1.0.2
 618      */
 619     public String getHostAddress() {
 620         return null;
 621      }
 622 
 623     /**
 624      * Returns a hashcode for this IP address.
 625      *
 626      * @return  a hash code value for this IP address.
 627      */
 628     public int hashCode() {
 629         return -1;
 630     }
 631 
 632     /**
 633      * Compares this object against the specified object.
 634      * The result is <code>true</code> if and only if the argument is
 635      * not <code>null</code> and it represents the same IP address as
 636      * this object.
 637      * <p>
 638      * Two instances of <code>InetAddress</code> represent the same IP
 639      * address if the length of the byte arrays returned by
 640      * <code>getAddress</code> is the same for both, and each of the
 641      * array components is the same for the byte arrays.
 642      *
 643      * @param   obj   the object to compare against.
 644      * @return  <code>true</code> if the objects are the same;
 645      *          <code>false</code> otherwise.
 646      * @see     java.net.InetAddress#getAddress()
 647      */
 648     public boolean equals(Object obj) {
 649         return false;
 650     }
 651 
 652     /**
 653      * Converts this IP address to a <code>String</code>. The
 654      * string returned is of the form: hostname / literal IP
 655      * address.
 656      *
 657      * If the host name is unresolved, no reverse name service lookup
 658      * is performed. The hostname part will be represented by an empty string.
 659      *
 660      * @return  a string representation of this IP address.
 661      */
 662     public String toString() {
 663         return ((hostName != null) ? hostName : "")
 664             + "/" + getHostAddress();
 665     }
 666 
 667     /*
 668      * Cached addresses - our own litle nis, not!
 669      */
 670     private static Cache addressCache = new Cache(Cache.Type.Positive);
 671 
 672     private static Cache negativeCache = new Cache(Cache.Type.Negative);
 673 
 674     private static boolean addressCacheInit = false;
 675 
 676     static InetAddress[]    unknown_array; // put THIS in cache
 677 
 678     static InetAddressImpl  impl;
 679 
 680     private static final HashMap<String, Void> lookupTable = new HashMap<>();
 681 
 682     /**
 683      * Represents a cache entry
 684      */
 685     static final class CacheEntry {
 686 
 687         CacheEntry(InetAddress[] addresses, long expiration) {
 688             this.addresses = addresses;
 689             this.expiration = expiration;
 690         }
 691 
 692         InetAddress[] addresses;
 693         long expiration;
 694     }
 695 
 696     /**
 697      * A cache that manages entries based on a policy specified
 698      * at creation time.
 699      */
 700     static final class Cache {
 701         private LinkedHashMap<String, CacheEntry> cache;
 702         private Type type;
 703 
 704         enum Type {Positive, Negative};
 705 
 706         /**
 707          * Create cache
 708          */
 709         public Cache(Type type) {
 710             this.type = type;
 711             cache = new LinkedHashMap<String, CacheEntry>();
 712         }
 713 
 714         private int getPolicy() {
 715             if (type == Type.Positive) {
 716                 return InetAddressCachePolicy.get();
 717             } else {
 718                 return InetAddressCachePolicy.getNegative();
 719             }
 720         }
 721 
 722         /**
 723          * Add an entry to the cache. If there's already an
 724          * entry then for this host then the entry will be
 725          * replaced.
 726          */
 727         public Cache put(String host, InetAddress[] addresses) {
 728             int policy = getPolicy();
 729             if (policy == InetAddressCachePolicy.NEVER) {
 730                 return this;
 731             }
 732 
 733             // purge any expired entries
 734 
 735             if (policy != InetAddressCachePolicy.FOREVER) {
 736 
 737                 // As we iterate in insertion order we can
 738                 // terminate when a non-expired entry is found.
 739                 LinkedList<String> expired = new LinkedList<>();
 740                 long now = System.currentTimeMillis();
 741                 for (String key : cache.keySet()) {
 742                     CacheEntry entry = cache.get(key);
 743 
 744                     if (entry.expiration >= 0 && entry.expiration < now) {
 745                         expired.add(key);
 746                     } else {
 747                         break;
 748                     }
 749                 }
 750 
 751                 for (String key : expired) {
 752                     cache.remove(key);
 753                 }
 754             }
 755 
 756             // create new entry and add it to the cache
 757             // -- as a HashMap replaces existing entries we
 758             //    don't need to explicitly check if there is
 759             //    already an entry for this host.
 760             long expiration;
 761             if (policy == InetAddressCachePolicy.FOREVER) {
 762                 expiration = -1;
 763             } else {
 764                 expiration = System.currentTimeMillis() + (policy * 1000);
 765             }
 766             CacheEntry entry = new CacheEntry(addresses, expiration);
 767             cache.put(host, entry);
 768             return this;
 769         }
 770 
 771         /**
 772          * Query the cache for the specific host. If found then
 773          * return its CacheEntry, or null if not found.
 774          */
 775         public CacheEntry get(String host) {
 776             int policy = getPolicy();
 777             if (policy == InetAddressCachePolicy.NEVER) {
 778                 return null;
 779             }
 780             CacheEntry entry = cache.get(host);
 781 
 782             // check if entry has expired
 783             if (entry != null && policy != InetAddressCachePolicy.FOREVER) {
 784                 if (entry.expiration >= 0 &&
 785                     entry.expiration < System.currentTimeMillis()) {
 786                     cache.remove(host);
 787                     entry = null;
 788                 }
 789             }
 790 
 791             return entry;
 792         }
 793     }
 794 
 795     /*
 796      * Initialize cache and insert anyLocalAddress into the
 797      * unknown array with no expiry.
 798      */
 799     private static void cacheInitIfNeeded() {
 800         assert Thread.holdsLock(addressCache);
 801         if (addressCacheInit) {
 802             return;
 803         }
 804         unknown_array = new InetAddress[1];
 805         unknown_array[0] = impl.anyLocalAddress();
 806 
 807         addressCache.put(impl.anyLocalAddress().getHostName(),
 808                          unknown_array);
 809 
 810         addressCacheInit = true;
 811     }
 812 
 813     /*
 814      * Cache the given hostname and addresses.
 815      */
 816     private static void cacheAddresses(String hostname,
 817                                        InetAddress[] addresses,
 818                                        boolean success) {
 819         hostname = hostname.toLowerCase();
 820         synchronized (addressCache) {
 821             cacheInitIfNeeded();
 822             if (success) {
 823                 addressCache.put(hostname, addresses);
 824             } else {
 825                 negativeCache.put(hostname, addresses);
 826             }
 827         }
 828     }
 829 
 830     /*
 831      * Lookup hostname in cache (positive & negative cache). If
 832      * found return addresses, null if not found.
 833      */
 834     private static InetAddress[] getCachedAddresses(String hostname) {
 835         hostname = hostname.toLowerCase();
 836 
 837         // search both positive & negative caches
 838 
 839         synchronized (addressCache) {
 840             cacheInitIfNeeded();
 841 
 842             CacheEntry entry = addressCache.get(hostname);
 843             if (entry == null) {
 844                 entry = negativeCache.get(hostname);
 845             }
 846 
 847             if (entry != null) {
 848                 return entry.addresses;
 849             }
 850         }
 851 
 852         // not found
 853         return null;
 854     }
 855 
 856     private static NameService createNSProvider(String provider) {
 857         if (provider == null)
 858             return null;
 859 
 860         NameService nameService = null;
 861         if (provider.equals("default")) {
 862             // initialize the default name service
 863             nameService = new NameService() {
 864                 public InetAddress[] lookupAllHostAddr(String host)
 865                     throws UnknownHostException {
 866                     return impl.lookupAllHostAddr(host);
 867                 }
 868                 public String getHostByAddr(byte[] addr)
 869                     throws UnknownHostException {
 870                     return impl.getHostByAddr(addr);
 871                 }
 872             };
 873         } else {
 874             final String providerName = provider;
 875             try {
 876                 nameService = java.security.AccessController.doPrivileged(
 877                     new java.security.PrivilegedExceptionAction<NameService>() {
 878                         public NameService run() {
 879                             Iterator<NameServiceDescriptor> itr =
 880                                 ServiceLoader.load(NameServiceDescriptor.class)
 881                                     .iterator();
 882                             while (itr.hasNext()) {
 883                                 NameServiceDescriptor nsd = itr.next();
 884                                 if (providerName.
 885                                     equalsIgnoreCase(nsd.getType()+","
 886                                         +nsd.getProviderName())) {
 887                                     try {
 888                                         return nsd.createNameService();
 889                                     } catch (Exception e) {
 890                                         e.printStackTrace();
 891                                         System.err.println(
 892                                             "Cannot create name service:"
 893                                              +providerName+": " + e);
 894                                     }
 895                                 }
 896                             }
 897 
 898                             return null;
 899                         }
 900                     }
 901                 );
 902             } catch (java.security.PrivilegedActionException e) {
 903             }
 904         }
 905 
 906         return nameService;
 907     }
 908 
 909     static {
 910         // create the impl
 911         impl = InetAddressImplFactory.create();
 912 
 913         // get name service if provided and requested
 914         String provider = null;;
 915         String propPrefix = "sun.net.spi.nameservice.provider.";
 916         int n = 1;
 917         nameServices = new ArrayList<NameService>();
 918         provider = AccessController.doPrivileged(
 919                 new GetPropertyAction(propPrefix + n));
 920         while (provider != null) {
 921             NameService ns = createNSProvider(provider);
 922             if (ns != null)
 923                 nameServices.add(ns);
 924 
 925             n++;
 926             provider = AccessController.doPrivileged(
 927                     new GetPropertyAction(propPrefix + n));
 928         }
 929 
 930         // if not designate any name services provider,
 931         // create a default one
 932         if (nameServices.size() == 0) {
 933             NameService ns = createNSProvider("default");
 934             nameServices.add(ns);
 935         }
 936     }
 937 
 938     /**
 939      * Creates an InetAddress based on the provided host name and IP address.
 940      * No name service is checked for the validity of the address.
 941      *
 942      * <p> The host name can either be a machine name, such as
 943      * "<code>java.sun.com</code>", or a textual representation of its IP
 944      * address.
 945      * <p> No validity checking is done on the host name either.
 946      *
 947      * <p> If addr specifies an IPv4 address an instance of Inet4Address
 948      * will be returned; otherwise, an instance of Inet6Address
 949      * will be returned.
 950      *
 951      * <p> IPv4 address byte array must be 4 bytes long and IPv6 byte array
 952      * must be 16 bytes long
 953      *
 954      * @param host the specified host
 955      * @param addr the raw IP address in network byte order
 956      * @return  an InetAddress object created from the raw IP address.
 957      * @exception  UnknownHostException  if IP address is of illegal length
 958      * @since 1.4
 959      */
 960     public static InetAddress getByAddress(String host, byte[] addr)
 961         throws UnknownHostException {
 962         if (host != null && host.length() > 0 && host.charAt(0) == '[') {
 963             if (host.charAt(host.length()-1) == ']') {
 964                 host = host.substring(1, host.length() -1);
 965             }
 966         }
 967         if (addr != null) {
 968             if (addr.length == Inet4Address.INADDRSZ) {
 969                 return new Inet4Address(host, addr);
 970             } else if (addr.length == Inet6Address.INADDRSZ) {
 971                 byte[] newAddr
 972                     = IPAddressUtil.convertFromIPv4MappedAddress(addr);
 973                 if (newAddr != null) {
 974                     return new Inet4Address(host, newAddr);
 975                 } else {
 976                     return new Inet6Address(host, addr);
 977                 }
 978             }
 979         }
 980         throw new UnknownHostException("addr is of illegal length");
 981     }
 982 
 983 
 984     /**
 985      * Determines the IP address of a host, given the host's name.
 986      *
 987      * <p> The host name can either be a machine name, such as
 988      * "<code>java.sun.com</code>", or a textual representation of its
 989      * IP address. If a literal IP address is supplied, only the
 990      * validity of the address format is checked.
 991      *
 992      * <p> For <code>host</code> specified in literal IPv6 address,
 993      * either the form defined in RFC 2732 or the literal IPv6 address
 994      * format defined in RFC 2373 is accepted. IPv6 scoped addresses are also
 995      * supported. See <a href="Inet6Address.html#scoped">here</a> for a description of IPv6
 996      * scoped addresses.
 997      *
 998      * <p> If the host is <tt>null</tt> then an <tt>InetAddress</tt>
 999      * representing an address of the loopback interface is returned.
1000      * See <a href="http://www.ietf.org/rfc/rfc3330.txt">RFC&nbsp;3330</a>
1001      * section&nbsp;2 and <a href="http://www.ietf.org/rfc/rfc2373.txt">RFC&nbsp;2373</a>
1002      * section&nbsp;2.5.3. </p>
1003      *
1004      * @param      host   the specified host, or <code>null</code>.
1005      * @return     an IP address for the given host name.
1006      * @exception  UnknownHostException  if no IP address for the
1007      *               <code>host</code> could be found, or if a scope_id was specified
1008      *               for a global IPv6 address.
1009      * @exception  SecurityException if a security manager exists
1010      *             and its checkConnect method doesn't allow the operation
1011      */
1012     public static InetAddress getByName(String host)
1013         throws UnknownHostException {
1014         return InetAddress.getAllByName(host)[0];
1015     }
1016 
1017     // called from deployment cache manager
1018     private static InetAddress getByName(String host, InetAddress reqAddr)
1019         throws UnknownHostException {
1020         return InetAddress.getAllByName(host, reqAddr)[0];
1021     }
1022 
1023     /**
1024      * Given the name of a host, returns an array of its IP addresses,
1025      * based on the configured name service on the system.
1026      *
1027      * <p> The host name can either be a machine name, such as
1028      * "<code>java.sun.com</code>", or a textual representation of its IP
1029      * address. If a literal IP address is supplied, only the
1030      * validity of the address format is checked.
1031      *
1032      * <p> For <code>host</code> specified in <i>literal IPv6 address</i>,
1033      * either the form defined in RFC 2732 or the literal IPv6 address
1034      * format defined in RFC 2373 is accepted. A literal IPv6 address may
1035      * also be qualified by appending a scoped zone identifier or scope_id.
1036      * The syntax and usage of scope_ids is described
1037      * <a href="Inet6Address.html#scoped">here</a>.
1038      * <p> If the host is <tt>null</tt> then an <tt>InetAddress</tt>
1039      * representing an address of the loopback interface is returned.
1040      * See <a href="http://www.ietf.org/rfc/rfc3330.txt">RFC&nbsp;3330</a>
1041      * section&nbsp;2 and <a href="http://www.ietf.org/rfc/rfc2373.txt">RFC&nbsp;2373</a>
1042      * section&nbsp;2.5.3. </p>
1043      *
1044      * <p> If there is a security manager and <code>host</code> is not
1045      * null and <code>host.length() </code> is not equal to zero, the
1046      * security manager's
1047      * <code>checkConnect</code> method is called
1048      * with the hostname and <code>-1</code>
1049      * as its arguments to see if the operation is allowed.
1050      *
1051      * @param      host   the name of the host, or <code>null</code>.
1052      * @return     an array of all the IP addresses for a given host name.
1053      *
1054      * @exception  UnknownHostException  if no IP address for the
1055      *               <code>host</code> could be found, or if a scope_id was specified
1056      *               for a global IPv6 address.
1057      * @exception  SecurityException  if a security manager exists and its
1058      *               <code>checkConnect</code> method doesn't allow the operation.
1059      *
1060      * @see SecurityManager#checkConnect
1061      */
1062     public static InetAddress[] getAllByName(String host)
1063         throws UnknownHostException {
1064         return getAllByName(host, null);
1065     }
1066 
1067     private static InetAddress[] getAllByName(String host, InetAddress reqAddr)
1068         throws UnknownHostException {
1069 
1070         if (host == null || host.length() == 0) {
1071             InetAddress[] ret = new InetAddress[1];
1072             ret[0] = impl.loopbackAddress();
1073             return ret;
1074         }
1075 
1076         boolean ipv6Expected = false;
1077         if (host.charAt(0) == '[') {
1078             // This is supposed to be an IPv6 literal
1079             if (host.length() > 2 && host.charAt(host.length()-1) == ']') {
1080                 host = host.substring(1, host.length() -1);
1081                 ipv6Expected = true;
1082             } else {
1083                 // This was supposed to be a IPv6 address, but it's not!
1084                 throw new UnknownHostException(host + ": invalid IPv6 address");
1085             }
1086         }
1087 
1088         // if host is an IP address, we won't do further lookup
1089         if (Character.digit(host.charAt(0), 16) != -1
1090             || (host.charAt(0) == ':')) {
1091             byte[] addr = null;
1092             int numericZone = -1;
1093             String ifname = null;
1094             // see if it is IPv4 address
1095             addr = IPAddressUtil.textToNumericFormatV4(host);
1096             if (addr == null) {
1097                 // see if it is IPv6 address
1098                 // Check if a numeric or string zone id is present
1099                 int pos;
1100                 if ((pos=host.indexOf ("%")) != -1) {
1101                     numericZone = checkNumericZone (host);
1102                     if (numericZone == -1) { /* remainder of string must be an ifname */
1103                         ifname = host.substring (pos+1);
1104                     }
1105                 }
1106                 addr = IPAddressUtil.textToNumericFormatV6(host);
1107             } else if (ipv6Expected) {
1108                 // Means an IPv4 litteral between brackets!
1109                 throw new UnknownHostException("["+host+"]");
1110             }
1111             InetAddress[] ret = new InetAddress[1];
1112             if(addr != null) {
1113                 if (addr.length == Inet4Address.INADDRSZ) {
1114                     ret[0] = new Inet4Address(null, addr);
1115                 } else {
1116                     if (ifname != null) {
1117                         ret[0] = new Inet6Address(null, addr, ifname);
1118                     } else {
1119                         ret[0] = new Inet6Address(null, addr, numericZone);
1120                     }
1121                 }
1122                 return ret;
1123             }
1124             } else if (ipv6Expected) {
1125                 // We were expecting an IPv6 Litteral, but got something else
1126                 throw new UnknownHostException("["+host+"]");
1127             }
1128         return getAllByName0(host, reqAddr, true);
1129     }
1130 
1131     /**
1132      * Returns the loopback address.
1133      * <p>
1134      * The InetAddress returned will represent the IPv4
1135      * loopback address, 127.0.0.1, or the IPv6 loopback
1136      * address, ::1. The IPv4 loopback address returned
1137      * is only one of many in the form 127.*.*.*
1138      *
1139      * @return  the InetAddress loopback instance.
1140      * @since 1.7
1141      */
1142     public static InetAddress getLoopbackAddress() {
1143         return impl.loopbackAddress();
1144     }
1145 
1146 
1147     /**
1148      * check if the literal address string has %nn appended
1149      * returns -1 if not, or the numeric value otherwise.
1150      *
1151      * %nn may also be a string that represents the displayName of
1152      * a currently available NetworkInterface.
1153      */
1154     private static int checkNumericZone (String s) throws UnknownHostException {
1155         int percent = s.indexOf ('%');
1156         int slen = s.length();
1157         int digit, zone=0;
1158         if (percent == -1) {
1159             return -1;
1160         }
1161         for (int i=percent+1; i<slen; i++) {
1162             char c = s.charAt(i);
1163             if (c == ']') {
1164                 if (i == percent+1) {
1165                     /* empty per-cent field */
1166                     return -1;
1167                 }
1168                 break;
1169             }
1170             if ((digit = Character.digit (c, 10)) < 0) {
1171                 return -1;
1172             }
1173             zone = (zone * 10) + digit;
1174         }
1175         return zone;
1176     }
1177 
1178     private static InetAddress[] getAllByName0 (String host)
1179         throws UnknownHostException
1180     {
1181         return getAllByName0(host, true);
1182     }
1183 
1184     /**
1185      * package private so SocketPermission can call it
1186      */
1187     static InetAddress[] getAllByName0 (String host, boolean check)
1188         throws UnknownHostException  {
1189         return getAllByName0 (host, null, check);
1190     }
1191 
1192     private static InetAddress[] getAllByName0 (String host, InetAddress reqAddr, boolean check)
1193         throws UnknownHostException  {
1194 
1195         /* If it gets here it is presumed to be a hostname */
1196         /* Cache.get can return: null, unknownAddress, or InetAddress[] */
1197 
1198         /* make sure the connection to the host is allowed, before we
1199          * give out a hostname
1200          */
1201         if (check) {
1202             SecurityManager security = System.getSecurityManager();
1203             if (security != null) {
1204                 security.checkConnect(host, -1);
1205             }
1206         }
1207 
1208         InetAddress[] addresses = getCachedAddresses(host);
1209 
1210         /* If no entry in cache, then do the host lookup */
1211         if (addresses == null) {
1212             addresses = getAddressesFromNameService(host, reqAddr);
1213         }
1214 
1215         if (addresses == unknown_array)
1216             throw new UnknownHostException(host);
1217 
1218         return addresses.clone();
1219     }
1220 
1221     private static InetAddress[] getAddressesFromNameService(String host, InetAddress reqAddr)
1222         throws UnknownHostException
1223     {
1224         InetAddress[] addresses = null;
1225         boolean success = false;
1226         UnknownHostException ex = null;
1227 
1228         // Check whether the host is in the lookupTable.
1229         // 1) If the host isn't in the lookupTable when
1230         //    checkLookupTable() is called, checkLookupTable()
1231         //    would add the host in the lookupTable and
1232         //    return null. So we will do the lookup.
1233         // 2) If the host is in the lookupTable when
1234         //    checkLookupTable() is called, the current thread
1235         //    would be blocked until the host is removed
1236         //    from the lookupTable. Then this thread
1237         //    should try to look up the addressCache.
1238         //     i) if it found the addresses in the
1239         //        addressCache, checkLookupTable()  would
1240         //        return the addresses.
1241         //     ii) if it didn't find the addresses in the
1242         //         addressCache for any reason,
1243         //         it should add the host in the
1244         //         lookupTable and return null so the
1245         //         following code would do  a lookup itself.
1246         if ((addresses = checkLookupTable(host)) == null) {
1247             try {
1248                 // This is the first thread which looks up the addresses
1249                 // this host or the cache entry for this host has been
1250                 // expired so this thread should do the lookup.
1251                 for (NameService nameService : nameServices) {
1252                     try {
1253                         /*
1254                          * Do not put the call to lookup() inside the
1255                          * constructor.  if you do you will still be
1256                          * allocating space when the lookup fails.
1257                          */
1258 
1259                         addresses = nameService.lookupAllHostAddr(host);
1260                         success = true;
1261                         break;
1262                     } catch (UnknownHostException uhe) {
1263                         if (host.equalsIgnoreCase("localhost")) {
1264                             InetAddress[] local = new InetAddress[] { impl.loopbackAddress() };
1265                             addresses = local;
1266                             success = true;
1267                             break;
1268                         }
1269                         else {
1270                             addresses = unknown_array;
1271                             success = false;
1272                             ex = uhe;
1273                         }
1274                     }
1275                 }
1276 
1277                 // More to do?
1278                 if (reqAddr != null && addresses.length > 1 && !addresses[0].equals(reqAddr)) {
1279                     // Find it?
1280                     int i = 1;
1281                     for (; i < addresses.length; i++) {
1282                         if (addresses[i].equals(reqAddr)) {
1283                             break;
1284                         }
1285                     }
1286                     // Rotate
1287                     if (i < addresses.length) {
1288                         InetAddress tmp, tmp2 = reqAddr;
1289                         for (int j = 0; j < i; j++) {
1290                             tmp = addresses[j];
1291                             addresses[j] = tmp2;
1292                             tmp2 = tmp;
1293                         }
1294                         addresses[i] = tmp2;
1295                     }
1296                 }
1297                 // Cache the address.
1298                 cacheAddresses(host, addresses, success);
1299 
1300                 if (!success && ex != null)
1301                     throw ex;
1302 
1303             } finally {
1304                 // Delete host from the lookupTable and notify
1305                 // all threads waiting on the lookupTable monitor.
1306                 updateLookupTable(host);
1307             }
1308         }
1309 
1310         return addresses;
1311     }
1312 
1313 
1314     private static InetAddress[] checkLookupTable(String host) {
1315         synchronized (lookupTable) {
1316             // If the host isn't in the lookupTable, add it in the
1317             // lookuptable and return null. The caller should do
1318             // the lookup.
1319             if (lookupTable.containsKey(host) == false) {
1320                 lookupTable.put(host, null);
1321                 return null;
1322             }
1323 
1324             // If the host is in the lookupTable, it means that another
1325             // thread is trying to look up the addresses of this host.
1326             // This thread should wait.
1327             while (lookupTable.containsKey(host)) {
1328                 try {
1329                     lookupTable.wait();
1330                 } catch (InterruptedException e) {
1331                 }
1332             }
1333         }
1334 
1335         // The other thread has finished looking up the addresses of
1336         // the host. This thread should retry to get the addresses
1337         // from the addressCache. If it doesn't get the addresses from
1338         // the cache, it will try to look up the addresses itself.
1339         InetAddress[] addresses = getCachedAddresses(host);
1340         if (addresses == null) {
1341             synchronized (lookupTable) {
1342                 lookupTable.put(host, null);
1343                 return null;
1344             }
1345         }
1346 
1347         return addresses;
1348     }
1349 
1350     private static void updateLookupTable(String host) {
1351         synchronized (lookupTable) {
1352             lookupTable.remove(host);
1353             lookupTable.notifyAll();
1354         }
1355     }
1356 
1357     /**
1358      * Returns an <code>InetAddress</code> object given the raw IP address .
1359      * The argument is in network byte order: the highest order
1360      * byte of the address is in <code>getAddress()[0]</code>.
1361      *
1362      * <p> This method doesn't block, i.e. no reverse name service lookup
1363      * is performed.
1364      *
1365      * <p> IPv4 address byte array must be 4 bytes long and IPv6 byte array
1366      * must be 16 bytes long
1367      *
1368      * @param addr the raw IP address in network byte order
1369      * @return  an InetAddress object created from the raw IP address.
1370      * @exception  UnknownHostException  if IP address is of illegal length
1371      * @since 1.4
1372      */
1373     public static InetAddress getByAddress(byte[] addr)
1374         throws UnknownHostException {
1375         return getByAddress(null, addr);
1376     }
1377 
1378     private static InetAddress cachedLocalHost = null;
1379     private static long cacheTime = 0;
1380     private static final long maxCacheTime = 5000L;
1381     private static final Object cacheLock = new Object();
1382 
1383     /**
1384      * Returns the address of the local host. This is achieved by retrieving
1385      * the name of the host from the system, then resolving that name into
1386      * an <code>InetAddress</code>.
1387      *
1388      * <P>Note: The resolved address may be cached for a short period of time.
1389      * </P>
1390      *
1391      * <p>If there is a security manager, its
1392      * <code>checkConnect</code> method is called
1393      * with the local host name and <code>-1</code>
1394      * as its arguments to see if the operation is allowed.
1395      * If the operation is not allowed, an InetAddress representing
1396      * the loopback address is returned.
1397      *
1398      * @return     the address of the local host.
1399      *
1400      * @exception  UnknownHostException  if the local host name could not
1401      *             be resolved into an address.
1402      *
1403      * @see SecurityManager#checkConnect
1404      * @see java.net.InetAddress#getByName(java.lang.String)
1405      */
1406     public static InetAddress getLocalHost() throws UnknownHostException {
1407 
1408         SecurityManager security = System.getSecurityManager();
1409         try {
1410             String local = impl.getLocalHostName();
1411 
1412             if (security != null) {
1413                 security.checkConnect(local, -1);
1414             }
1415 
1416             if (local.equals("localhost")) {
1417                 return impl.loopbackAddress();
1418             }
1419 
1420             InetAddress ret = null;
1421             synchronized (cacheLock) {
1422                 long now = System.currentTimeMillis();
1423                 if (cachedLocalHost != null) {
1424                     if ((now - cacheTime) < maxCacheTime) // Less than 5s old?
1425                         ret = cachedLocalHost;
1426                     else
1427                         cachedLocalHost = null;
1428                 }
1429 
1430                 // we are calling getAddressesFromNameService directly
1431                 // to avoid getting localHost from cache
1432                 if (ret == null) {
1433                     InetAddress[] localAddrs;
1434                     try {
1435                         localAddrs =
1436                             InetAddress.getAddressesFromNameService(local, null);
1437                     } catch (UnknownHostException uhe) {
1438                         // Rethrow with a more informative error message.
1439                         UnknownHostException uhe2 =
1440                             new UnknownHostException(local + ": " +
1441                                                      uhe.getMessage());
1442                         uhe2.initCause(uhe);
1443                         throw uhe2;
1444                     }
1445                     cachedLocalHost = localAddrs[0];
1446                     cacheTime = now;
1447                     ret = localAddrs[0];
1448                 }
1449             }
1450             return ret;
1451         } catch (java.lang.SecurityException e) {
1452             return impl.loopbackAddress();
1453         }
1454     }
1455 
1456     /**
1457      * Perform class load-time initializations.
1458      */
1459     private static native void init();
1460 
1461 
1462     /*
1463      * Returns the InetAddress representing anyLocalAddress
1464      * (typically 0.0.0.0 or ::0)
1465      */
1466     static InetAddress anyLocalAddress() {
1467         return impl.anyLocalAddress();
1468     }
1469 
1470     /*
1471      * Load and instantiate an underlying impl class
1472      */
1473     static InetAddressImpl loadImpl(String implName) {
1474         Object impl = null;
1475 
1476         /*
1477          * Property "impl.prefix" will be prepended to the classname
1478          * of the implementation object we instantiate, to which we
1479          * delegate the real work (like native methods).  This
1480          * property can vary across implementations of the java.
1481          * classes.  The default is an empty String "".
1482          */
1483         String prefix = AccessController.doPrivileged(
1484                       new GetPropertyAction("impl.prefix", ""));
1485         try {
1486             impl = Class.forName("java.net." + prefix + implName).newInstance();
1487         } catch (ClassNotFoundException e) {
1488             System.err.println("Class not found: java.net." + prefix +
1489                                implName + ":\ncheck impl.prefix property " +
1490                                "in your properties file.");
1491         } catch (InstantiationException e) {
1492             System.err.println("Could not instantiate: java.net." + prefix +
1493                                implName + ":\ncheck impl.prefix property " +
1494                                "in your properties file.");
1495         } catch (IllegalAccessException e) {
1496             System.err.println("Cannot access class: java.net." + prefix +
1497                                implName + ":\ncheck impl.prefix property " +
1498                                "in your properties file.");
1499         }
1500 
1501         if (impl == null) {
1502             try {
1503                 impl = Class.forName(implName).newInstance();
1504             } catch (Exception e) {
1505                 throw new Error("System property impl.prefix incorrect");
1506             }
1507         }
1508 
1509         return (InetAddressImpl) impl;
1510     }
1511 
1512     private void readObjectNoData (ObjectInputStream s) throws
1513                          IOException, ClassNotFoundException {
1514         if (getClass().getClassLoader() != null) {
1515             throw new SecurityException ("invalid address type");
1516         }
1517     }
1518 
1519     private void readObject (ObjectInputStream s) throws
1520                          IOException, ClassNotFoundException {
1521         s.defaultReadObject ();
1522         if (getClass().getClassLoader() != null) {
1523             hostName = null;
1524             address = 0;
1525             throw new SecurityException ("invalid address type");
1526         }
1527     }
1528 }
1529 
1530 /*
1531  * Simple factory to create the impl
1532  */
1533 class InetAddressImplFactory {
1534 
1535     static InetAddressImpl create() {
1536         return InetAddress.loadImpl(isIPv6Supported() ?
1537                                     "Inet6AddressImpl" : "Inet4AddressImpl");
1538     }
1539 
1540     static native boolean isIPv6Supported();
1541 }