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