1 /*
   2  * Copyright (c) 1995, 2010, 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.security.AccessController;
  36 import java.io.ObjectStreamException;
  37 import java.io.IOException;
  38 import java.io.ObjectInputStream;
  39 import sun.security.action.*;
  40 import sun.net.InetAddressCachePolicy;
  41 import sun.net.util.IPAddressUtil;
  42 import sun.misc.Service;
  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 HashMap<String, InetAddress[]> lookupTable
 681         = new HashMap<String, InetAddress[]>();
 682 
 683     /**
 684      * Represents a cache entry
 685      */
 686     static final class CacheEntry {
 687 
 688         CacheEntry(InetAddress[] addresses, long expiration) {
 689             this.addresses = addresses;
 690             this.expiration = expiration;
 691         }
 692 
 693         InetAddress[] addresses;
 694         long expiration;
 695     }
 696 
 697     /**
 698      * A cache that manages entries based on a policy specified
 699      * at creation time.
 700      */
 701     static final class Cache {
 702         private LinkedHashMap<String, CacheEntry> cache;
 703         private Type type;
 704 
 705         enum Type {Positive, Negative};
 706 
 707         /**
 708          * Create cache
 709          */
 710         public Cache(Type type) {
 711             this.type = type;
 712             cache = new LinkedHashMap<String, CacheEntry>();
 713         }
 714 
 715         private int getPolicy() {
 716             if (type == Type.Positive) {
 717                 return InetAddressCachePolicy.get();
 718             } else {
 719                 return InetAddressCachePolicy.getNegative();
 720             }
 721         }
 722 
 723         /**
 724          * Add an entry to the cache. If there's already an
 725          * entry then for this host then the entry will be
 726          * replaced.
 727          */
 728         public Cache put(String host, InetAddress[] addresses) {
 729             int policy = getPolicy();
 730             if (policy == InetAddressCachePolicy.NEVER) {
 731                 return this;
 732             }
 733 
 734             // purge any expired entries
 735 
 736             if (policy != InetAddressCachePolicy.FOREVER) {
 737 
 738                 // As we iterate in insertion order we can
 739                 // terminate when a non-expired entry is found.
 740                 LinkedList<String> expired = new LinkedList<String>();
 741                 long now = System.currentTimeMillis();
 742                 for (String key : cache.keySet()) {
 743                     CacheEntry entry = cache.get(key);
 744 
 745                     if (entry.expiration >= 0 && entry.expiration < now) {
 746                         expired.add(key);
 747                     } else {
 748                         break;
 749                     }
 750                 }
 751 
 752                 for (String key : expired) {
 753                     cache.remove(key);
 754                 }
 755             }
 756 
 757             // create new entry and add it to the cache
 758             // -- as a HashMap replaces existing entries we
 759             //    don't need to explicitly check if there is
 760             //    already an entry for this host.
 761             long expiration;
 762             if (policy == InetAddressCachePolicy.FOREVER) {
 763                 expiration = -1;
 764             } else {
 765                 expiration = System.currentTimeMillis() + (policy * 1000);
 766             }
 767             CacheEntry entry = new CacheEntry(addresses, expiration);
 768             cache.put(host, entry);
 769             return this;
 770         }
 771 
 772         /**
 773          * Query the cache for the specific host. If found then
 774          * return its CacheEntry, or null if not found.
 775          */
 776         public CacheEntry get(String host) {
 777             int policy = getPolicy();
 778             if (policy == InetAddressCachePolicy.NEVER) {
 779                 return null;
 780             }
 781             CacheEntry entry = cache.get(host);
 782 
 783             // check if entry has expired
 784             if (entry != null && policy != InetAddressCachePolicy.FOREVER) {
 785                 if (entry.expiration >= 0 &&
 786                     entry.expiration < System.currentTimeMillis()) {
 787                     cache.remove(host);
 788                     entry = null;
 789                 }
 790             }
 791 
 792             return entry;
 793         }
 794     }
 795 
 796     /*
 797      * Initialize cache and insert anyLocalAddress into the
 798      * unknown array with no expiry.
 799      */
 800     private static void cacheInitIfNeeded() {
 801         assert Thread.holdsLock(addressCache);
 802         if (addressCacheInit) {
 803             return;
 804         }
 805         unknown_array = new InetAddress[1];
 806         unknown_array[0] = impl.anyLocalAddress();
 807 
 808         addressCache.put(impl.anyLocalAddress().getHostName(),
 809                          unknown_array);
 810 
 811         addressCacheInit = true;
 812     }
 813 
 814     /*
 815      * Cache the given hostname and addresses.
 816      */
 817     private static void cacheAddresses(String hostname,
 818                                        InetAddress[] addresses,
 819                                        boolean success) {
 820         hostname = hostname.toLowerCase();
 821         synchronized (addressCache) {
 822             cacheInitIfNeeded();
 823             if (success) {
 824                 addressCache.put(hostname, addresses);
 825             } else {
 826                 negativeCache.put(hostname, addresses);
 827             }
 828         }
 829     }
 830 
 831     /*
 832      * Lookup hostname in cache (positive & negative cache). If
 833      * found return addresses, null if not found.
 834      */
 835     private static InetAddress[] getCachedAddresses(String hostname) {
 836         hostname = hostname.toLowerCase();
 837 
 838         // search both positive & negative caches
 839 
 840         synchronized (addressCache) {
 841             cacheInitIfNeeded();
 842 
 843             CacheEntry entry = addressCache.get(hostname);
 844             if (entry == null) {
 845                 entry = negativeCache.get(hostname);
 846             }
 847 
 848             if (entry != null) {
 849                 return entry.addresses;
 850             }
 851         }
 852 
 853         // not found
 854         return null;
 855     }
 856 
 857     private static NameService createNSProvider(String provider) {
 858         if (provider == null)
 859             return null;
 860 
 861         NameService nameService = null;
 862         if (provider.equals("default")) {
 863             // initialize the default name service
 864             nameService = new NameService() {
 865                 public InetAddress[] lookupAllHostAddr(String host)
 866                     throws UnknownHostException {
 867                     return impl.lookupAllHostAddr(host);
 868                 }
 869                 public String getHostByAddr(byte[] addr)
 870                     throws UnknownHostException {
 871                     return impl.getHostByAddr(addr);
 872                 }
 873             };
 874         } else {
 875             final String providerName = provider;
 876             try {
 877                 nameService = java.security.AccessController.doPrivileged(
 878                     new java.security.PrivilegedExceptionAction<NameService>() {
 879                         public NameService run() {
 880                             Iterator itr = Service.providers(NameServiceDescriptor.class);
 881                             while (itr.hasNext()) {
 882                                 NameServiceDescriptor nsd
 883                                     = (NameServiceDescriptor)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     /**
1018      * Given the name of a host, returns an array of its IP addresses,
1019      * based on the configured name service on the system.
1020      *
1021      * <p> The host name can either be a machine name, such as
1022      * "<code>java.sun.com</code>", or a textual representation of its IP
1023      * address. If a literal IP address is supplied, only the
1024      * validity of the address format is checked.
1025      *
1026      * <p> For <code>host</code> specified in <i>literal IPv6 address</i>,
1027      * either the form defined in RFC 2732 or the literal IPv6 address
1028      * format defined in RFC 2373 is accepted. A literal IPv6 address may
1029      * also be qualified by appending a scoped zone identifier or scope_id.
1030      * The syntax and usage of scope_ids is described
1031      * <a href="Inet6Address.html#scoped">here</a>.
1032      * <p> If the host is <tt>null</tt> then an <tt>InetAddress</tt>
1033      * representing an address of the loopback interface is returned.
1034      * See <a href="http://www.ietf.org/rfc/rfc3330.txt">RFC&nbsp;3330</a>
1035      * section&nbsp;2 and <a href="http://www.ietf.org/rfc/rfc2373.txt">RFC&nbsp;2373</a>
1036      * section&nbsp;2.5.3. </p>
1037      *
1038      * <p> If there is a security manager and <code>host</code> is not
1039      * null and <code>host.length() </code> is not equal to zero, the
1040      * security manager's
1041      * <code>checkConnect</code> method is called
1042      * with the hostname and <code>-1</code>
1043      * as its arguments to see if the operation is allowed.
1044      *
1045      * @param      host   the name of the host, or <code>null</code>.
1046      * @return     an array of all the IP addresses for a given host name.
1047      *
1048      * @exception  UnknownHostException  if no IP address for the
1049      *               <code>host</code> could be found, or if a scope_id was specified
1050      *               for a global IPv6 address.
1051      * @exception  SecurityException  if a security manager exists and its
1052      *               <code>checkConnect</code> method doesn't allow the operation.
1053      *
1054      * @see SecurityManager#checkConnect
1055      */
1056     public static InetAddress[] getAllByName(String host)
1057         throws UnknownHostException {
1058 
1059         if (host == null || host.length() == 0) {
1060             InetAddress[] ret = new InetAddress[1];
1061             ret[0] = impl.loopbackAddress();
1062             return ret;
1063         }
1064 
1065         boolean ipv6Expected = false;
1066         if (host.charAt(0) == '[') {
1067             // This is supposed to be an IPv6 literal
1068             if (host.length() > 2 && host.charAt(host.length()-1) == ']') {
1069                 host = host.substring(1, host.length() -1);
1070                 ipv6Expected = true;
1071             } else {
1072                 // This was supposed to be a IPv6 address, but it's not!
1073                 throw new UnknownHostException(host + ": invalid IPv6 address");
1074             }
1075         }
1076 
1077         // if host is an IP address, we won't do further lookup
1078         if (Character.digit(host.charAt(0), 16) != -1
1079             || (host.charAt(0) == ':')) {
1080             byte[] addr = null;
1081             int numericZone = -1;
1082             String ifname = null;
1083             // see if it is IPv4 address
1084             addr = IPAddressUtil.textToNumericFormatV4(host);
1085             if (addr == null) {
1086                 // see if it is IPv6 address
1087                 // Check if a numeric or string zone id is present
1088                 int pos;
1089                 if ((pos=host.indexOf ("%")) != -1) {
1090                     numericZone = checkNumericZone (host);
1091                     if (numericZone == -1) { /* remainder of string must be an ifname */
1092                         ifname = host.substring (pos+1);
1093                     }
1094                 }
1095                 addr = IPAddressUtil.textToNumericFormatV6(host);
1096             } else if (ipv6Expected) {
1097                 // Means an IPv4 litteral between brackets!
1098                 throw new UnknownHostException("["+host+"]");
1099             }
1100             InetAddress[] ret = new InetAddress[1];
1101             if(addr != null) {
1102                 if (addr.length == Inet4Address.INADDRSZ) {
1103                     ret[0] = new Inet4Address(null, addr);
1104                 } else {
1105                     if (ifname != null) {
1106                         ret[0] = new Inet6Address(null, addr, ifname);
1107                     } else {
1108                         ret[0] = new Inet6Address(null, addr, numericZone);
1109                     }
1110                 }
1111                 return ret;
1112             }
1113             } else if (ipv6Expected) {
1114                 // We were expecting an IPv6 Litteral, but got something else
1115                 throw new UnknownHostException("["+host+"]");
1116             }
1117         return getAllByName0(host);
1118     }
1119 
1120     /**
1121      * Returns the loopback address.
1122      * <p>
1123      * The InetAddress returned will represent the IPv4
1124      * loopback address, 127.0.0.1, or the IPv6 loopback
1125      * address, ::1. The IPv4 loopback address returned
1126      * is only one of many in the form 127.*.*.*
1127      *
1128      * @return  the InetAddress loopback instance.
1129      * @since 1.7
1130      */
1131     public static InetAddress getLoopbackAddress() {
1132         return impl.loopbackAddress();
1133     }
1134 
1135 
1136     /**
1137      * check if the literal address string has %nn appended
1138      * returns -1 if not, or the numeric value otherwise.
1139      *
1140      * %nn may also be a string that represents the displayName of
1141      * a currently available NetworkInterface.
1142      */
1143     private static int checkNumericZone (String s) throws UnknownHostException {
1144         int percent = s.indexOf ('%');
1145         int slen = s.length();
1146         int digit, zone=0;
1147         if (percent == -1) {
1148             return -1;
1149         }
1150         for (int i=percent+1; i<slen; i++) {
1151             char c = s.charAt(i);
1152             if (c == ']') {
1153                 if (i == percent+1) {
1154                     /* empty per-cent field */
1155                     return -1;
1156                 }
1157                 break;
1158             }
1159             if ((digit = Character.digit (c, 10)) < 0) {
1160                 return -1;
1161             }
1162             zone = (zone * 10) + digit;
1163         }
1164         return zone;
1165     }
1166 
1167     private static InetAddress[] getAllByName0 (String host)
1168         throws UnknownHostException
1169     {
1170         return getAllByName0(host, true);
1171     }
1172 
1173     /**
1174      * package private so SocketPermission can call it
1175      */
1176     static InetAddress[] getAllByName0 (String host, boolean check)
1177         throws UnknownHostException  {
1178         /* If it gets here it is presumed to be a hostname */
1179         /* Cache.get can return: null, unknownAddress, or InetAddress[] */
1180 
1181         /* make sure the connection to the host is allowed, before we
1182          * give out a hostname
1183          */
1184         if (check) {
1185             SecurityManager security = System.getSecurityManager();
1186             if (security != null) {
1187                 security.checkConnect(host, -1);
1188             }
1189         }
1190 
1191         InetAddress[] addresses = getCachedAddresses(host);
1192 
1193         /* If no entry in cache, then do the host lookup */
1194         if (addresses == null) {
1195             addresses = getAddressesFromNameService(host);
1196         }
1197 
1198         if (addresses == unknown_array)
1199             throw new UnknownHostException(host);
1200 
1201         return addresses.clone();
1202     }
1203 
1204     private static InetAddress[] getAddressesFromNameService(String host)
1205         throws UnknownHostException
1206     {
1207         InetAddress[] addresses = null;
1208         boolean success = false;
1209         UnknownHostException ex = null;
1210 
1211         // Check whether the host is in the lookupTable.
1212         // 1) If the host isn't in the lookupTable when
1213         //    checkLookupTable() is called, checkLookupTable()
1214         //    would add the host in the lookupTable and
1215         //    return null. So we will do the lookup.
1216         // 2) If the host is in the lookupTable when
1217         //    checkLookupTable() is called, the current thread
1218         //    would be blocked until the host is removed
1219         //    from the lookupTable. Then this thread
1220         //    should try to look up the addressCache.
1221         //     i) if it found the addresses in the
1222         //        addressCache, checkLookupTable()  would
1223         //        return the addresses.
1224         //     ii) if it didn't find the addresses in the
1225         //         addressCache for any reason,
1226         //         it should add the host in the
1227         //         lookupTable and return null so the
1228         //         following code would do  a lookup itself.
1229         if ((addresses = checkLookupTable(host)) == null) {
1230             // This is the first thread which looks up the addresses
1231             // this host or the cache entry for this host has been
1232             // expired so this thread should do the lookup.
1233             for (NameService nameService : nameServices) {
1234                 try {
1235                     /*
1236                      * Do not put the call to lookup() inside the
1237                      * constructor.  if you do you will still be
1238                      * allocating space when the lookup fails.
1239                      */
1240 
1241                     addresses = nameService.lookupAllHostAddr(host);
1242                     success = true;
1243                     break;
1244                 } catch (UnknownHostException uhe) {
1245                     if (host.equalsIgnoreCase("localhost")) {
1246                         InetAddress[] local = new InetAddress[] { impl.loopbackAddress() };
1247                         addresses = local;
1248                         success = true;
1249                         break;
1250                     }
1251                     else {
1252                         addresses = unknown_array;
1253                         success = false;
1254                         ex = uhe;
1255                     }
1256                 }
1257             }
1258 
1259             // Cache the addresses.
1260             cacheAddresses(host, addresses, success);
1261             // Delete the host from the lookupTable, and
1262             // notify all threads waiting for the monitor
1263             // for lookupTable.
1264             updateLookupTable(host);
1265             if (!success && ex != null)
1266                 throw ex;
1267         }
1268 
1269         return addresses;
1270     }
1271 
1272 
1273     private static InetAddress[] checkLookupTable(String host) {
1274         // make sure addresses is null.
1275         InetAddress[] addresses = null;
1276 
1277         synchronized (lookupTable) {
1278             // If the host isn't in the lookupTable, add it in the
1279             // lookuptable and return null. The caller should do
1280             // the lookup.
1281             if (lookupTable.containsKey(host) == false) {
1282                 lookupTable.put(host, null);
1283                 return addresses;
1284             }
1285 
1286             // If the host is in the lookupTable, it means that another
1287             // thread is trying to look up the addresses of this host.
1288             // This thread should wait.
1289             while (lookupTable.containsKey(host)) {
1290                 try {
1291                     lookupTable.wait();
1292                 } catch (InterruptedException e) {
1293                 }
1294             }
1295         }
1296 
1297         // The other thread has finished looking up the addresses of
1298         // the host. This thread should retry to get the addresses
1299         // from the addressCache. If it doesn't get the addresses from
1300         // the cache, it will try to look up the addresses itself.
1301         addresses = getCachedAddresses(host);
1302         if (addresses == null) {
1303             synchronized (lookupTable) {
1304                 lookupTable.put(host, null);
1305             }
1306         }
1307 
1308         return addresses;
1309     }
1310 
1311     private static void updateLookupTable(String host) {
1312         synchronized (lookupTable) {
1313             lookupTable.remove(host);
1314             lookupTable.notifyAll();
1315         }
1316     }
1317 
1318     /**
1319      * Returns an <code>InetAddress</code> object given the raw IP address .
1320      * The argument is in network byte order: the highest order
1321      * byte of the address is in <code>getAddress()[0]</code>.
1322      *
1323      * <p> This method doesn't block, i.e. no reverse name service lookup
1324      * is performed.
1325      *
1326      * <p> IPv4 address byte array must be 4 bytes long and IPv6 byte array
1327      * must be 16 bytes long
1328      *
1329      * @param addr the raw IP address in network byte order
1330      * @return  an InetAddress object created from the raw IP address.
1331      * @exception  UnknownHostException  if IP address is of illegal length
1332      * @since 1.4
1333      */
1334     public static InetAddress getByAddress(byte[] addr)
1335         throws UnknownHostException {
1336         return getByAddress(null, addr);
1337     }
1338 
1339     private static InetAddress cachedLocalHost = null;
1340     private static long cacheTime = 0;
1341     private static final long maxCacheTime = 5000L;
1342     private static final Object cacheLock = new Object();
1343 
1344     /**
1345      * Returns the address of the local host. This is achieved by retrieving
1346      * the name of the host from the system, then resolving that name into
1347      * an <code>InetAddress</code>.
1348      *
1349      * <P>Note: The resolved address may be cached for a short period of time.
1350      * </P>
1351      *
1352      * <p>If there is a security manager, its
1353      * <code>checkConnect</code> method is called
1354      * with the local host name and <code>-1</code>
1355      * as its arguments to see if the operation is allowed.
1356      * If the operation is not allowed, an InetAddress representing
1357      * the loopback address is returned.
1358      *
1359      * @return     the address of the local host.
1360      *
1361      * @exception  UnknownHostException  if the local host name could not
1362      *             be resolved into an address.
1363      *
1364      * @see SecurityManager#checkConnect
1365      * @see java.net.InetAddress#getByName(java.lang.String)
1366      */
1367     public static InetAddress getLocalHost() throws UnknownHostException {
1368 
1369         SecurityManager security = System.getSecurityManager();
1370         try {
1371             String local = impl.getLocalHostName();
1372 
1373             if (security != null) {
1374                 security.checkConnect(local, -1);
1375             }
1376 
1377             if (local.equals("localhost")) {
1378                 return impl.loopbackAddress();
1379             }
1380 
1381             InetAddress ret = null;
1382             synchronized (cacheLock) {
1383                 long now = System.currentTimeMillis();
1384                 if (cachedLocalHost != null) {
1385                     if ((now - cacheTime) < maxCacheTime) // Less than 5s old?
1386                         ret = cachedLocalHost;
1387                     else
1388                         cachedLocalHost = null;
1389                 }
1390 
1391                 // we are calling getAddressesFromNameService directly
1392                 // to avoid getting localHost from cache
1393                 if (ret == null) {
1394                     InetAddress[] localAddrs;
1395                     try {
1396                         localAddrs =
1397                             InetAddress.getAddressesFromNameService(local);
1398                     } catch (UnknownHostException uhe) {
1399                         // Rethrow with a more informative error message.
1400                         UnknownHostException uhe2 =
1401                             new UnknownHostException(local + ": " +
1402                                                      uhe.getMessage());
1403                         uhe2.initCause(uhe);
1404                         throw uhe2;
1405                     }
1406                     cachedLocalHost = localAddrs[0];
1407                     cacheTime = now;
1408                     ret = localAddrs[0];
1409                 }
1410             }
1411             return ret;
1412         } catch (java.lang.SecurityException e) {
1413             return impl.loopbackAddress();
1414         }
1415     }
1416 
1417     /**
1418      * Perform class load-time initializations.
1419      */
1420     private static native void init();
1421 
1422 
1423     /*
1424      * Returns the InetAddress representing anyLocalAddress
1425      * (typically 0.0.0.0 or ::0)
1426      */
1427     static InetAddress anyLocalAddress() {
1428         return impl.anyLocalAddress();
1429     }
1430 
1431     /*
1432      * Load and instantiate an underlying impl class
1433      */
1434     static InetAddressImpl loadImpl(String implName) {
1435         Object impl = null;
1436 
1437         /*
1438          * Property "impl.prefix" will be prepended to the classname
1439          * of the implementation object we instantiate, to which we
1440          * delegate the real work (like native methods).  This
1441          * property can vary across implementations of the java.
1442          * classes.  The default is an empty String "".
1443          */
1444         String prefix = AccessController.doPrivileged(
1445                       new GetPropertyAction("impl.prefix", ""));
1446         try {
1447             impl = Class.forName("java.net." + prefix + implName).newInstance();
1448         } catch (ClassNotFoundException e) {
1449             System.err.println("Class not found: java.net." + prefix +
1450                                implName + ":\ncheck impl.prefix property " +
1451                                "in your properties file.");
1452         } catch (InstantiationException e) {
1453             System.err.println("Could not instantiate: java.net." + prefix +
1454                                implName + ":\ncheck impl.prefix property " +
1455                                "in your properties file.");
1456         } catch (IllegalAccessException e) {
1457             System.err.println("Cannot access class: java.net." + prefix +
1458                                implName + ":\ncheck impl.prefix property " +
1459                                "in your properties file.");
1460         }
1461 
1462         if (impl == null) {
1463             try {
1464                 impl = Class.forName(implName).newInstance();
1465             } catch (Exception e) {
1466                 throw new Error("System property impl.prefix incorrect");
1467             }
1468         }
1469 
1470         return (InetAddressImpl) impl;
1471     }
1472 
1473     private void readObjectNoData (ObjectInputStream s) throws
1474                          IOException, ClassNotFoundException {
1475         if (getClass().getClassLoader() != null) {
1476             throw new SecurityException ("invalid address type");
1477         }
1478     }
1479 
1480     private void readObject (ObjectInputStream s) throws
1481                          IOException, ClassNotFoundException {
1482         s.defaultReadObject ();
1483         if (getClass().getClassLoader() != null) {
1484             hostName = null;
1485             address = 0;
1486             throw new SecurityException ("invalid address type");
1487         }
1488     }
1489 }
1490 
1491 /*
1492  * Simple factory to create the impl
1493  */
1494 class InetAddressImplFactory {
1495 
1496     static InetAddressImpl create() {
1497         return InetAddress.loadImpl(isIPv6Supported() ?
1498                                     "Inet6AddressImpl" : "Inet4AddressImpl");
1499     }
1500 
1501     static native boolean isIPv6Supported();
1502 }