0N/A/*
3909N/A * Copyright (c) 1995, 2011, Oracle and/or its affiliates. All rights reserved.
0N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
0N/A *
0N/A * This code is free software; you can redistribute it and/or modify it
0N/A * under the terms of the GNU General Public License version 2 only, as
2362N/A * published by the Free Software Foundation. Oracle designates this
0N/A * particular file as subject to the "Classpath" exception as provided
2362N/A * by Oracle in the LICENSE file that accompanied this code.
0N/A *
0N/A * This code is distributed in the hope that it will be useful, but WITHOUT
0N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
0N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
0N/A * version 2 for more details (a copy is included in the LICENSE file that
0N/A * accompanied this code).
0N/A *
0N/A * You should have received a copy of the GNU General Public License version
0N/A * 2 along with this work; if not, write to the Free Software Foundation,
0N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
0N/A *
2362N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
2362N/A * or visit www.oracle.com if you need additional information or have any
2362N/A * questions.
0N/A */
0N/A
0N/Apackage java.net;
0N/A
0N/Aimport java.util.HashMap;
0N/Aimport java.util.LinkedHashMap;
0N/Aimport java.util.Random;
0N/Aimport java.util.Iterator;
0N/Aimport java.util.LinkedList;
0N/Aimport java.util.List;
0N/Aimport java.util.ArrayList;
0N/Aimport java.security.AccessController;
0N/Aimport java.io.ObjectStreamException;
5888N/Aimport java.io.ObjectStreamField;
0N/Aimport java.io.IOException;
2259N/Aimport java.io.ObjectInputStream;
5888N/Aimport java.io.ObjectInputStream.GetField;
5888N/Aimport java.io.ObjectOutputStream;
5888N/Aimport java.io.ObjectOutputStream.PutField;
0N/Aimport sun.security.action.*;
0N/Aimport sun.net.InetAddressCachePolicy;
0N/Aimport sun.net.util.IPAddressUtil;
0N/Aimport sun.misc.Service;
0N/Aimport sun.net.spi.nameservice.*;
0N/A
0N/A/**
0N/A * This class represents an Internet Protocol (IP) address.
0N/A *
0N/A * <p> An IP address is either a 32-bit or 128-bit unsigned number
0N/A * used by IP, a lower-level protocol on which protocols like UDP and
0N/A * TCP are built. The IP address architecture is defined by <a
0N/A * href="http://www.ietf.org/rfc/rfc790.txt"><i>RFC&nbsp;790:
0N/A * Assigned Numbers</i></a>, <a
0N/A * href="http://www.ietf.org/rfc/rfc1918.txt"> <i>RFC&nbsp;1918:
0N/A * Address Allocation for Private Internets</i></a>, <a
0N/A * href="http://www.ietf.org/rfc/rfc2365.txt"><i>RFC&nbsp;2365:
0N/A * Administratively Scoped IP Multicast</i></a>, and <a
0N/A * href="http://www.ietf.org/rfc/rfc2373.txt"><i>RFC&nbsp;2373: IP
0N/A * Version 6 Addressing Architecture</i></a>. An instance of an
0N/A * InetAddress consists of an IP address and possibly its
0N/A * corresponding host name (depending on whether it is constructed
0N/A * with a host name or whether it has already done reverse host name
0N/A * resolution).
0N/A *
0N/A * <h4> Address types </h4>
0N/A *
0N/A * <blockquote><table cellspacing=2 summary="Description of unicast and multicast address types">
0N/A * <tr><th valign=top><i>unicast</i></th>
0N/A * <td>An identifier for a single interface. A packet sent to
0N/A * a unicast address is delivered to the interface identified by
0N/A * that address.
0N/A *
0N/A * <p> The Unspecified Address -- Also called anylocal or wildcard
0N/A * address. It must never be assigned to any node. It indicates the
0N/A * absence of an address. One example of its use is as the target of
0N/A * bind, which allows a server to accept a client connection on any
0N/A * interface, in case the server host has multiple interfaces.
0N/A *
0N/A * <p> The <i>unspecified</i> address must not be used as
0N/A * the destination address of an IP packet.
0N/A *
0N/A * <p> The <i>Loopback</i> Addresses -- This is the address
0N/A * assigned to the loopback interface. Anything sent to this
0N/A * IP address loops around and becomes IP input on the local
0N/A * host. This address is often used when testing a
0N/A * client.</td></tr>
0N/A * <tr><th valign=top><i>multicast</i></th>
0N/A * <td>An identifier for a set of interfaces (typically belonging
0N/A * to different nodes). A packet sent to a multicast address is
0N/A * delivered to all interfaces identified by that address.</td></tr>
0N/A * </table></blockquote>
0N/A *
0N/A * <h4> IP address scope </h4>
0N/A *
0N/A * <p> <i>Link-local</i> addresses are designed to be used for addressing
0N/A * on a single link for purposes such as auto-address configuration,
0N/A * neighbor discovery, or when no routers are present.
0N/A *
0N/A * <p> <i>Site-local</i> addresses are designed to be used for addressing
0N/A * inside of a site without the need for a global prefix.
0N/A *
0N/A * <p> <i>Global</i> addresses are unique across the internet.
0N/A *
0N/A * <h4> Textual representation of IP addresses </h4>
0N/A *
0N/A * The textual representation of an IP address is address family specific.
0N/A *
0N/A * <p>
0N/A *
0N/A * For IPv4 address format, please refer to <A
0N/A * HREF="Inet4Address.html#format">Inet4Address#format</A>; For IPv6
0N/A * address format, please refer to <A
0N/A * HREF="Inet6Address.html#format">Inet6Address#format</A>.
0N/A *
0N/A * <P>There is a <a href="doc-files/net-properties.html#Ipv4IPv6">couple of
0N/A * System Properties</a> affecting how IPv4 and IPv6 addresses are used.</P>
0N/A *
0N/A * <h4> Host Name Resolution </h4>
0N/A *
0N/A * Host name-to-IP address <i>resolution</i> is accomplished through
0N/A * the use of a combination of local machine configuration information
0N/A * and network naming services such as the Domain Name System (DNS)
0N/A * and Network Information Service(NIS). The particular naming
0N/A * services(s) being used is by default the local machine configured
0N/A * one. For any host name, its corresponding IP address is returned.
0N/A *
0N/A * <p> <i>Reverse name resolution</i> means that for any IP address,
0N/A * the host associated with the IP address is returned.
0N/A *
0N/A * <p> The InetAddress class provides methods to resolve host names to
0N/A * their IP addresses and vice versa.
0N/A *
0N/A * <h4> InetAddress Caching </h4>
0N/A *
0N/A * The InetAddress class has a cache to store successful as well as
0N/A * unsuccessful host name resolutions.
0N/A *
0N/A * <p> By default, when a security manager is installed, in order to
0N/A * protect against DNS spoofing attacks,
0N/A * the result of positive host name resolutions are
0N/A * cached forever. When a security manager is not installed, the default
0N/A * behavior is to cache entries for a finite (implementation dependent)
0N/A * period of time. The result of unsuccessful host
0N/A * name resolution is cached for a very short period of time (10
0N/A * seconds) to improve performance.
0N/A *
0N/A * <p> If the default behavior is not desired, then a Java security property
0N/A * can be set to a different Time-to-live (TTL) value for positive
0N/A * caching. Likewise, a system admin can configure a different
0N/A * negative caching TTL value when needed.
0N/A *
0N/A * <p> Two Java security properties control the TTL values used for
0N/A * positive and negative host name resolution caching:
0N/A *
0N/A * <blockquote>
0N/A * <dl>
0N/A * <dt><b>networkaddress.cache.ttl</b></dt>
0N/A * <dd>Indicates the caching policy for successful name lookups from
0N/A * the name service. The value is specified as as integer to indicate
0N/A * the number of seconds to cache the successful lookup. The default
0N/A * setting is to cache for an implementation specific period of time.
0N/A * <p>
0N/A * A value of -1 indicates "cache forever".
0N/A * </dd>
0N/A * <p>
0N/A * <dt><b>networkaddress.cache.negative.ttl</b> (default: 10)</dt>
0N/A * <dd>Indicates the caching policy for un-successful name lookups
0N/A * from the name service. The value is specified as as integer to
0N/A * indicate the number of seconds to cache the failure for
0N/A * un-successful lookups.
0N/A * <p>
0N/A * A value of 0 indicates "never cache".
0N/A * A value of -1 indicates "cache forever".
0N/A * </dd>
0N/A * </dl>
0N/A * </blockquote>
0N/A *
0N/A * @author Chris Warth
0N/A * @see java.net.InetAddress#getByAddress(byte[])
0N/A * @see java.net.InetAddress#getByAddress(java.lang.String, byte[])
0N/A * @see java.net.InetAddress#getAllByName(java.lang.String)
0N/A * @see java.net.InetAddress#getByName(java.lang.String)
0N/A * @see java.net.InetAddress#getLocalHost()
0N/A * @since JDK1.0
0N/A */
0N/Apublic
0N/Aclass InetAddress implements java.io.Serializable {
0N/A /**
0N/A * Specify the address family: Internet Protocol, Version 4
0N/A * @since 1.4
0N/A */
0N/A static final int IPv4 = 1;
0N/A
0N/A /**
0N/A * Specify the address family: Internet Protocol, Version 6
0N/A * @since 1.4
0N/A */
0N/A static final int IPv6 = 2;
0N/A
0N/A /* Specify address family preference */
0N/A static transient boolean preferIPv6Address = false;
0N/A
5888N/A static class InetAddressHolder {
5888N/A
5888N/A InetAddressHolder() {}
5888N/A
5888N/A InetAddressHolder(String hostName, int address, int family) {
5888N/A this.hostName = hostName;
5888N/A this.address = address;
5888N/A this.family = family;
5888N/A }
5888N/A
5888N/A String hostName;
5888N/A
5888N/A String getHostName() {
5888N/A return hostName;
5888N/A }
5888N/A
5888N/A /**
5888N/A * Holds a 32-bit IPv4 address.
5888N/A */
5888N/A int address;
0N/A
5888N/A int getAddress() {
5888N/A return address;
5888N/A }
5888N/A
5888N/A /**
5888N/A * Specifies the address family type, for instance, '1' for IPv4
5888N/A * addresses, and '2' for IPv6 addresses.
5888N/A */
5888N/A int family;
0N/A
5888N/A int getFamily() {
5888N/A return family;
5888N/A }
5888N/A }
5888N/A
5888N/A final transient InetAddressHolder holder;
5888N/A
5888N/A InetAddressHolder holder() {
5888N/A return holder;
5888N/A }
0N/A
0N/A /* Used to store the name service provider */
0N/A private static List<NameService> nameServices = null;
0N/A
0N/A /* Used to store the best available hostname */
0N/A private transient String canonicalHostName = null;
0N/A
0N/A /** use serialVersionUID from JDK 1.0.2 for interoperability */
0N/A private static final long serialVersionUID = 3286316764910316507L;
0N/A
0N/A /*
0N/A * Load net library into runtime, and perform initializations.
0N/A */
0N/A static {
0N/A preferIPv6Address = java.security.AccessController.doPrivileged(
0N/A new GetBooleanAction("java.net.preferIPv6Addresses")).booleanValue();
0N/A AccessController.doPrivileged(new LoadLibraryAction("net"));
0N/A init();
0N/A }
0N/A
0N/A /**
0N/A * Constructor for the Socket.accept() method.
0N/A * This creates an empty InetAddress, which is filled in by
0N/A * the accept() method. This InetAddress, however, is not
0N/A * put in the address cache, since it is not created by name.
0N/A */
0N/A InetAddress() {
5888N/A holder = new InetAddressHolder();
0N/A }
0N/A
0N/A /**
0N/A * Replaces the de-serialized object with an Inet4Address object.
0N/A *
0N/A * @return the alternate object to the de-serialized object.
0N/A *
0N/A * @throws ObjectStreamException if a new object replacing this
0N/A * object could not be created
0N/A */
0N/A private Object readResolve() throws ObjectStreamException {
0N/A // will replace the deserialized 'this' object
5888N/A return new Inet4Address(holder().getHostName(), holder().getAddress());
0N/A }
0N/A
0N/A /**
0N/A * Utility routine to check if the InetAddress is an
0N/A * IP multicast address.
0N/A * @return a <code>boolean</code> indicating if the InetAddress is
0N/A * an IP multicast address
0N/A * @since JDK1.1
0N/A */
0N/A public boolean isMulticastAddress() {
0N/A return false;
0N/A }
0N/A
0N/A /**
0N/A * Utility routine to check if the InetAddress in a wildcard address.
0N/A * @return a <code>boolean</code> indicating if the Inetaddress is
0N/A * a wildcard address.
0N/A * @since 1.4
0N/A */
0N/A public boolean isAnyLocalAddress() {
0N/A return false;
0N/A }
0N/A
0N/A /**
0N/A * Utility routine to check if the InetAddress is a loopback address.
0N/A *
0N/A * @return a <code>boolean</code> indicating if the InetAddress is
0N/A * a loopback address; or false otherwise.
0N/A * @since 1.4
0N/A */
0N/A public boolean isLoopbackAddress() {
0N/A return false;
0N/A }
0N/A
0N/A /**
0N/A * Utility routine to check if the InetAddress is an link local address.
0N/A *
0N/A * @return a <code>boolean</code> indicating if the InetAddress is
0N/A * a link local address; or false if address is not a link local unicast address.
0N/A * @since 1.4
0N/A */
0N/A public boolean isLinkLocalAddress() {
0N/A return false;
0N/A }
0N/A
0N/A /**
0N/A * Utility routine to check if the InetAddress is a site local address.
0N/A *
0N/A * @return a <code>boolean</code> indicating if the InetAddress is
0N/A * a site local address; or false if address is not a site local unicast address.
0N/A * @since 1.4
0N/A */
0N/A public boolean isSiteLocalAddress() {
0N/A return false;
0N/A }
0N/A
0N/A /**
0N/A * Utility routine to check if the multicast address has global scope.
0N/A *
0N/A * @return a <code>boolean</code> indicating if the address has
0N/A * is a multicast address of global scope, false if it is not
0N/A * of global scope or it is not a multicast address
0N/A * @since 1.4
0N/A */
0N/A public boolean isMCGlobal() {
0N/A return false;
0N/A }
0N/A
0N/A /**
0N/A * Utility routine to check if the multicast address has node scope.
0N/A *
0N/A * @return a <code>boolean</code> indicating if the address has
0N/A * is a multicast address of node-local scope, false if it is not
0N/A * of node-local scope or it is not a multicast address
0N/A * @since 1.4
0N/A */
0N/A public boolean isMCNodeLocal() {
0N/A return false;
0N/A }
0N/A
0N/A /**
0N/A * Utility routine to check if the multicast address has link scope.
0N/A *
0N/A * @return a <code>boolean</code> indicating if the address has
0N/A * is a multicast address of link-local scope, false if it is not
0N/A * of link-local scope or it is not a multicast address
0N/A * @since 1.4
0N/A */
0N/A public boolean isMCLinkLocal() {
0N/A return false;
0N/A }
0N/A
0N/A /**
0N/A * Utility routine to check if the multicast address has site scope.
0N/A *
0N/A * @return a <code>boolean</code> indicating if the address has
0N/A * is a multicast address of site-local scope, false if it is not
0N/A * of site-local scope or it is not a multicast address
0N/A * @since 1.4
0N/A */
0N/A public boolean isMCSiteLocal() {
0N/A return false;
0N/A }
0N/A
0N/A /**
0N/A * Utility routine to check if the multicast address has organization scope.
0N/A *
0N/A * @return a <code>boolean</code> indicating if the address has
0N/A * is a multicast address of organization-local scope,
0N/A * false if it is not of organization-local scope
0N/A * or it is not a multicast address
0N/A * @since 1.4
0N/A */
0N/A public boolean isMCOrgLocal() {
0N/A return false;
0N/A }
0N/A
0N/A
0N/A /**
0N/A * Test whether that address is reachable. Best effort is made by the
0N/A * implementation to try to reach the host, but firewalls and server
0N/A * configuration may block requests resulting in a unreachable status
0N/A * while some specific ports may be accessible.
0N/A * A typical implementation will use ICMP ECHO REQUESTs if the
0N/A * privilege can be obtained, otherwise it will try to establish
0N/A * a TCP connection on port 7 (Echo) of the destination host.
0N/A * <p>
0N/A * The timeout value, in milliseconds, indicates the maximum amount of time
0N/A * the try should take. If the operation times out before getting an
0N/A * answer, the host is deemed unreachable. A negative value will result
0N/A * in an IllegalArgumentException being thrown.
0N/A *
0N/A * @param timeout the time, in milliseconds, before the call aborts
0N/A * @return a <code>boolean</code> indicating if the address is reachable.
0N/A * @throws IOException if a network error occurs
0N/A * @throws IllegalArgumentException if <code>timeout</code> is negative.
0N/A * @since 1.5
0N/A */
0N/A public boolean isReachable(int timeout) throws IOException {
0N/A return isReachable(null, 0 , timeout);
0N/A }
0N/A
0N/A /**
0N/A * Test whether that address is reachable. Best effort is made by the
0N/A * implementation to try to reach the host, but firewalls and server
0N/A * configuration may block requests resulting in a unreachable status
0N/A * while some specific ports may be accessible.
0N/A * A typical implementation will use ICMP ECHO REQUESTs if the
0N/A * privilege can be obtained, otherwise it will try to establish
0N/A * a TCP connection on port 7 (Echo) of the destination host.
0N/A * <p>
0N/A * The <code>network interface</code> and <code>ttl</code> parameters
0N/A * let the caller specify which network interface the test will go through
0N/A * and the maximum number of hops the packets should go through.
0N/A * A negative value for the <code>ttl</code> will result in an
0N/A * IllegalArgumentException being thrown.
0N/A * <p>
0N/A * The timeout value, in milliseconds, indicates the maximum amount of time
0N/A * the try should take. If the operation times out before getting an
0N/A * answer, the host is deemed unreachable. A negative value will result
0N/A * in an IllegalArgumentException being thrown.
0N/A *
0N/A * @param netif the NetworkInterface through which the
0N/A * test will be done, or null for any interface
0N/A * @param ttl the maximum numbers of hops to try or 0 for the
0N/A * default
0N/A * @param timeout the time, in milliseconds, before the call aborts
0N/A * @throws IllegalArgumentException if either <code>timeout</code>
0N/A * or <code>ttl</code> are negative.
0N/A * @return a <code>boolean</code>indicating if the address is reachable.
0N/A * @throws IOException if a network error occurs
0N/A * @since 1.5
0N/A */
0N/A public boolean isReachable(NetworkInterface netif, int ttl,
0N/A int timeout) throws IOException {
0N/A if (ttl < 0)
0N/A throw new IllegalArgumentException("ttl can't be negative");
0N/A if (timeout < 0)
0N/A throw new IllegalArgumentException("timeout can't be negative");
0N/A
0N/A return impl.isReachable(this, timeout, netif, ttl);
0N/A }
0N/A
0N/A /**
0N/A * Gets the host name for this IP address.
0N/A *
0N/A * <p>If this InetAddress was created with a host name,
0N/A * this host name will be remembered and returned;
0N/A * otherwise, a reverse name lookup will be performed
0N/A * and the result will be returned based on the system
0N/A * configured name lookup service. If a lookup of the name service
0N/A * is required, call
0N/A * {@link #getCanonicalHostName() getCanonicalHostName}.
0N/A *
0N/A * <p>If there is a security manager, its
0N/A * <code>checkConnect</code> method is first called
0N/A * with the hostname and <code>-1</code>
0N/A * as its arguments to see if the operation is allowed.
0N/A * If the operation is not allowed, it will return
0N/A * the textual representation of the IP address.
0N/A *
0N/A * @return the host name for this IP address, or if the operation
0N/A * is not allowed by the security check, the textual
0N/A * representation of the IP address.
0N/A *
0N/A * @see InetAddress#getCanonicalHostName
0N/A * @see SecurityManager#checkConnect
0N/A */
0N/A public String getHostName() {
0N/A return getHostName(true);
0N/A }
0N/A
0N/A /**
0N/A * Returns the hostname for this address.
0N/A * If the host is equal to null, then this address refers to any
0N/A * of the local machine's available network addresses.
0N/A * this is package private so SocketPermission can make calls into
0N/A * here without a security check.
0N/A *
0N/A * <p>If there is a security manager, this method first
0N/A * calls its <code>checkConnect</code> method
0N/A * with the hostname and <code>-1</code>
0N/A * as its arguments to see if the calling code is allowed to know
0N/A * the hostname for this IP address, i.e., to connect to the host.
0N/A * If the operation is not allowed, it will return
0N/A * the textual representation of the IP address.
0N/A *
0N/A * @return the host name for this IP address, or if the operation
0N/A * is not allowed by the security check, the textual
0N/A * representation of the IP address.
0N/A *
0N/A * @param check make security check if true
0N/A *
0N/A * @see SecurityManager#checkConnect
0N/A */
0N/A String getHostName(boolean check) {
5888N/A if (holder().getHostName() == null) {
5888N/A holder().hostName = InetAddress.getHostFromNameService(this, check);
0N/A }
5888N/A return holder().getHostName();
0N/A }
0N/A
0N/A /**
0N/A * Gets the fully qualified domain name for this IP address.
0N/A * Best effort method, meaning we may not be able to return
0N/A * the FQDN depending on the underlying system configuration.
0N/A *
0N/A * <p>If there is a security manager, this method first
0N/A * calls its <code>checkConnect</code> method
0N/A * with the hostname and <code>-1</code>
0N/A * as its arguments to see if the calling code is allowed to know
0N/A * the hostname for this IP address, i.e., to connect to the host.
0N/A * If the operation is not allowed, it will return
0N/A * the textual representation of the IP address.
0N/A *
0N/A * @return the fully qualified domain name for this IP address,
0N/A * or if the operation is not allowed by the security check,
0N/A * the textual representation of the IP address.
0N/A *
0N/A * @see SecurityManager#checkConnect
0N/A *
0N/A * @since 1.4
0N/A */
0N/A public String getCanonicalHostName() {
0N/A if (canonicalHostName == null) {
0N/A canonicalHostName =
0N/A InetAddress.getHostFromNameService(this, true);
0N/A }
0N/A return canonicalHostName;
0N/A }
0N/A
0N/A /**
0N/A * Returns the hostname for this address.
0N/A *
0N/A * <p>If there is a security manager, this method first
0N/A * calls its <code>checkConnect</code> method
0N/A * with the hostname and <code>-1</code>
0N/A * as its arguments to see if the calling code is allowed to know
0N/A * the hostname for this IP address, i.e., to connect to the host.
0N/A * If the operation is not allowed, it will return
0N/A * the textual representation of the IP address.
0N/A *
0N/A * @return the host name for this IP address, or if the operation
0N/A * is not allowed by the security check, the textual
0N/A * representation of the IP address.
0N/A *
0N/A * @param check make security check if true
0N/A *
0N/A * @see SecurityManager#checkConnect
0N/A */
0N/A private static String getHostFromNameService(InetAddress addr, boolean check) {
0N/A String host = null;
0N/A for (NameService nameService : nameServices) {
0N/A try {
0N/A // first lookup the hostname
0N/A host = nameService.getHostByAddr(addr.getAddress());
0N/A
0N/A /* check to see if calling code is allowed to know
0N/A * the hostname for this IP address, ie, connect to the host
0N/A */
0N/A if (check) {
0N/A SecurityManager sec = System.getSecurityManager();
0N/A if (sec != null) {
0N/A sec.checkConnect(host, -1);
0N/A }
0N/A }
0N/A
0N/A /* now get all the IP addresses for this hostname,
0N/A * and make sure one of them matches the original IP
0N/A * address. We do this to try and prevent spoofing.
0N/A */
0N/A
0N/A InetAddress[] arr = InetAddress.getAllByName0(host, check);
0N/A boolean ok = false;
0N/A
0N/A if(arr != null) {
0N/A for(int i = 0; !ok && i < arr.length; i++) {
0N/A ok = addr.equals(arr[i]);
0N/A }
0N/A }
0N/A
0N/A //XXX: if it looks a spoof just return the address?
0N/A if (!ok) {
0N/A host = addr.getHostAddress();
0N/A return host;
0N/A }
0N/A
0N/A break;
0N/A
0N/A } catch (SecurityException e) {
0N/A host = addr.getHostAddress();
0N/A break;
0N/A } catch (UnknownHostException e) {
0N/A host = addr.getHostAddress();
0N/A // let next provider resolve the hostname
0N/A }
0N/A }
0N/A
0N/A return host;
0N/A }
0N/A
0N/A /**
0N/A * Returns the raw IP address of this <code>InetAddress</code>
0N/A * object. The result is in network byte order: the highest order
0N/A * byte of the address is in <code>getAddress()[0]</code>.
0N/A *
0N/A * @return the raw IP address of this object.
0N/A */
0N/A public byte[] getAddress() {
0N/A return null;
0N/A }
0N/A
0N/A /**
0N/A * Returns the IP address string in textual presentation.
0N/A *
0N/A * @return the raw IP address in a string format.
0N/A * @since JDK1.0.2
0N/A */
0N/A public String getHostAddress() {
0N/A return null;
0N/A }
0N/A
0N/A /**
0N/A * Returns a hashcode for this IP address.
0N/A *
0N/A * @return a hash code value for this IP address.
0N/A */
0N/A public int hashCode() {
0N/A return -1;
0N/A }
0N/A
0N/A /**
0N/A * Compares this object against the specified object.
0N/A * The result is <code>true</code> if and only if the argument is
0N/A * not <code>null</code> and it represents the same IP address as
0N/A * this object.
0N/A * <p>
0N/A * Two instances of <code>InetAddress</code> represent the same IP
0N/A * address if the length of the byte arrays returned by
0N/A * <code>getAddress</code> is the same for both, and each of the
0N/A * array components is the same for the byte arrays.
0N/A *
0N/A * @param obj the object to compare against.
0N/A * @return <code>true</code> if the objects are the same;
0N/A * <code>false</code> otherwise.
0N/A * @see java.net.InetAddress#getAddress()
0N/A */
0N/A public boolean equals(Object obj) {
0N/A return false;
0N/A }
0N/A
0N/A /**
0N/A * Converts this IP address to a <code>String</code>. The
0N/A * string returned is of the form: hostname / literal IP
0N/A * address.
0N/A *
0N/A * If the host name is unresolved, no reverse name service lookup
0N/A * is performed. The hostname part will be represented by an empty string.
0N/A *
0N/A * @return a string representation of this IP address.
0N/A */
0N/A public String toString() {
5888N/A String hostName = holder().getHostName();
0N/A return ((hostName != null) ? hostName : "")
0N/A + "/" + getHostAddress();
0N/A }
0N/A
0N/A /*
0N/A * Cached addresses - our own litle nis, not!
0N/A */
0N/A private static Cache addressCache = new Cache(Cache.Type.Positive);
0N/A
0N/A private static Cache negativeCache = new Cache(Cache.Type.Negative);
0N/A
0N/A private static boolean addressCacheInit = false;
0N/A
0N/A static InetAddress[] unknown_array; // put THIS in cache
0N/A
0N/A static InetAddressImpl impl;
0N/A
3406N/A private static final HashMap<String, Void> lookupTable = new HashMap<>();
0N/A
0N/A /**
0N/A * Represents a cache entry
0N/A */
0N/A static final class CacheEntry {
0N/A
2801N/A CacheEntry(InetAddress[] addresses, long expiration) {
2801N/A this.addresses = addresses;
0N/A this.expiration = expiration;
0N/A }
0N/A
2801N/A InetAddress[] addresses;
0N/A long expiration;
0N/A }
0N/A
0N/A /**
0N/A * A cache that manages entries based on a policy specified
0N/A * at creation time.
0N/A */
0N/A static final class Cache {
2801N/A private LinkedHashMap<String, CacheEntry> cache;
0N/A private Type type;
0N/A
0N/A enum Type {Positive, Negative};
0N/A
0N/A /**
0N/A * Create cache
0N/A */
0N/A public Cache(Type type) {
0N/A this.type = type;
2801N/A cache = new LinkedHashMap<String, CacheEntry>();
0N/A }
0N/A
0N/A private int getPolicy() {
0N/A if (type == Type.Positive) {
0N/A return InetAddressCachePolicy.get();
0N/A } else {
0N/A return InetAddressCachePolicy.getNegative();
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Add an entry to the cache. If there's already an
0N/A * entry then for this host then the entry will be
0N/A * replaced.
0N/A */
2801N/A public Cache put(String host, InetAddress[] addresses) {
0N/A int policy = getPolicy();
0N/A if (policy == InetAddressCachePolicy.NEVER) {
0N/A return this;
0N/A }
0N/A
0N/A // purge any expired entries
0N/A
0N/A if (policy != InetAddressCachePolicy.FOREVER) {
0N/A
0N/A // As we iterate in insertion order we can
0N/A // terminate when a non-expired entry is found.
3406N/A LinkedList<String> expired = new LinkedList<>();
0N/A long now = System.currentTimeMillis();
2801N/A for (String key : cache.keySet()) {
2801N/A CacheEntry entry = cache.get(key);
0N/A
0N/A if (entry.expiration >= 0 && entry.expiration < now) {
0N/A expired.add(key);
0N/A } else {
0N/A break;
0N/A }
0N/A }
0N/A
2801N/A for (String key : expired) {
2801N/A cache.remove(key);
0N/A }
0N/A }
0N/A
0N/A // create new entry and add it to the cache
0N/A // -- as a HashMap replaces existing entries we
0N/A // don't need to explicitly check if there is
0N/A // already an entry for this host.
0N/A long expiration;
0N/A if (policy == InetAddressCachePolicy.FOREVER) {
0N/A expiration = -1;
0N/A } else {
0N/A expiration = System.currentTimeMillis() + (policy * 1000);
0N/A }
2801N/A CacheEntry entry = new CacheEntry(addresses, expiration);
0N/A cache.put(host, entry);
0N/A return this;
0N/A }
0N/A
0N/A /**
0N/A * Query the cache for the specific host. If found then
0N/A * return its CacheEntry, or null if not found.
0N/A */
0N/A public CacheEntry get(String host) {
0N/A int policy = getPolicy();
0N/A if (policy == InetAddressCachePolicy.NEVER) {
0N/A return null;
0N/A }
2801N/A CacheEntry entry = cache.get(host);
0N/A
0N/A // check if entry has expired
0N/A if (entry != null && policy != InetAddressCachePolicy.FOREVER) {
0N/A if (entry.expiration >= 0 &&
0N/A entry.expiration < System.currentTimeMillis()) {
0N/A cache.remove(host);
0N/A entry = null;
0N/A }
0N/A }
0N/A
0N/A return entry;
0N/A }
0N/A }
0N/A
0N/A /*
0N/A * Initialize cache and insert anyLocalAddress into the
0N/A * unknown array with no expiry.
0N/A */
0N/A private static void cacheInitIfNeeded() {
0N/A assert Thread.holdsLock(addressCache);
0N/A if (addressCacheInit) {
0N/A return;
0N/A }
0N/A unknown_array = new InetAddress[1];
0N/A unknown_array[0] = impl.anyLocalAddress();
0N/A
0N/A addressCache.put(impl.anyLocalAddress().getHostName(),
0N/A unknown_array);
0N/A
0N/A addressCacheInit = true;
0N/A }
0N/A
0N/A /*
2801N/A * Cache the given hostname and addresses.
0N/A */
2801N/A private static void cacheAddresses(String hostname,
2801N/A InetAddress[] addresses,
2801N/A boolean success) {
0N/A hostname = hostname.toLowerCase();
0N/A synchronized (addressCache) {
0N/A cacheInitIfNeeded();
0N/A if (success) {
2801N/A addressCache.put(hostname, addresses);
0N/A } else {
2801N/A negativeCache.put(hostname, addresses);
0N/A }
0N/A }
0N/A }
0N/A
0N/A /*
0N/A * Lookup hostname in cache (positive & negative cache). If
2801N/A * found return addresses, null if not found.
0N/A */
2801N/A private static InetAddress[] getCachedAddresses(String hostname) {
0N/A hostname = hostname.toLowerCase();
0N/A
0N/A // search both positive & negative caches
0N/A
0N/A synchronized (addressCache) {
0N/A cacheInitIfNeeded();
0N/A
2801N/A CacheEntry entry = addressCache.get(hostname);
0N/A if (entry == null) {
0N/A entry = negativeCache.get(hostname);
0N/A }
0N/A
0N/A if (entry != null) {
2801N/A return entry.addresses;
0N/A }
0N/A }
0N/A
0N/A // not found
0N/A return null;
0N/A }
0N/A
0N/A private static NameService createNSProvider(String provider) {
0N/A if (provider == null)
0N/A return null;
0N/A
0N/A NameService nameService = null;
0N/A if (provider.equals("default")) {
0N/A // initialize the default name service
0N/A nameService = new NameService() {
0N/A public InetAddress[] lookupAllHostAddr(String host)
0N/A throws UnknownHostException {
0N/A return impl.lookupAllHostAddr(host);
0N/A }
0N/A public String getHostByAddr(byte[] addr)
0N/A throws UnknownHostException {
0N/A return impl.getHostByAddr(addr);
0N/A }
0N/A };
0N/A } else {
0N/A final String providerName = provider;
0N/A try {
0N/A nameService = java.security.AccessController.doPrivileged(
0N/A new java.security.PrivilegedExceptionAction<NameService>() {
0N/A public NameService run() {
0N/A Iterator itr = Service.providers(NameServiceDescriptor.class);
0N/A while (itr.hasNext()) {
0N/A NameServiceDescriptor nsd
0N/A = (NameServiceDescriptor)itr.next();
0N/A if (providerName.
0N/A equalsIgnoreCase(nsd.getType()+","
0N/A +nsd.getProviderName())) {
0N/A try {
0N/A return nsd.createNameService();
0N/A } catch (Exception e) {
0N/A e.printStackTrace();
0N/A System.err.println(
0N/A "Cannot create name service:"
0N/A +providerName+": " + e);
0N/A }
0N/A }
0N/A }
0N/A
0N/A return null;
0N/A }
0N/A }
0N/A );
0N/A } catch (java.security.PrivilegedActionException e) {
0N/A }
0N/A }
0N/A
0N/A return nameService;
0N/A }
0N/A
0N/A static {
0N/A // create the impl
2801N/A impl = InetAddressImplFactory.create();
0N/A
0N/A // get name service if provided and requested
0N/A String provider = null;;
0N/A String propPrefix = "sun.net.spi.nameservice.provider.";
0N/A int n = 1;
0N/A nameServices = new ArrayList<NameService>();
0N/A provider = AccessController.doPrivileged(
0N/A new GetPropertyAction(propPrefix + n));
0N/A while (provider != null) {
0N/A NameService ns = createNSProvider(provider);
0N/A if (ns != null)
0N/A nameServices.add(ns);
0N/A
0N/A n++;
0N/A provider = AccessController.doPrivileged(
0N/A new GetPropertyAction(propPrefix + n));
0N/A }
0N/A
0N/A // if not designate any name services provider,
2801N/A // create a default one
0N/A if (nameServices.size() == 0) {
0N/A NameService ns = createNSProvider("default");
0N/A nameServices.add(ns);
0N/A }
0N/A }
0N/A
0N/A /**
2801N/A * Creates an InetAddress based on the provided host name and IP address.
0N/A * No name service is checked for the validity of the address.
0N/A *
0N/A * <p> The host name can either be a machine name, such as
0N/A * "<code>java.sun.com</code>", or a textual representation of its IP
0N/A * address.
0N/A * <p> No validity checking is done on the host name either.
0N/A *
0N/A * <p> If addr specifies an IPv4 address an instance of Inet4Address
0N/A * will be returned; otherwise, an instance of Inet6Address
0N/A * will be returned.
0N/A *
0N/A * <p> IPv4 address byte array must be 4 bytes long and IPv6 byte array
0N/A * must be 16 bytes long
0N/A *
0N/A * @param host the specified host
0N/A * @param addr the raw IP address in network byte order
0N/A * @return an InetAddress object created from the raw IP address.
0N/A * @exception UnknownHostException if IP address is of illegal length
0N/A * @since 1.4
0N/A */
0N/A public static InetAddress getByAddress(String host, byte[] addr)
0N/A throws UnknownHostException {
0N/A if (host != null && host.length() > 0 && host.charAt(0) == '[') {
0N/A if (host.charAt(host.length()-1) == ']') {
0N/A host = host.substring(1, host.length() -1);
0N/A }
0N/A }
0N/A if (addr != null) {
0N/A if (addr.length == Inet4Address.INADDRSZ) {
0N/A return new Inet4Address(host, addr);
0N/A } else if (addr.length == Inet6Address.INADDRSZ) {
0N/A byte[] newAddr
0N/A = IPAddressUtil.convertFromIPv4MappedAddress(addr);
0N/A if (newAddr != null) {
0N/A return new Inet4Address(host, newAddr);
0N/A } else {
0N/A return new Inet6Address(host, addr);
0N/A }
0N/A }
0N/A }
0N/A throw new UnknownHostException("addr is of illegal length");
0N/A }
0N/A
0N/A
0N/A /**
0N/A * Determines the IP address of a host, given the host's name.
0N/A *
0N/A * <p> The host name can either be a machine name, such as
0N/A * "<code>java.sun.com</code>", or a textual representation of its
0N/A * IP address. If a literal IP address is supplied, only the
0N/A * validity of the address format is checked.
0N/A *
0N/A * <p> For <code>host</code> specified in literal IPv6 address,
0N/A * either the form defined in RFC 2732 or the literal IPv6 address
0N/A * format defined in RFC 2373 is accepted. IPv6 scoped addresses are also
0N/A * supported. See <a href="Inet6Address.html#scoped">here</a> for a description of IPv6
0N/A * scoped addresses.
0N/A *
0N/A * <p> If the host is <tt>null</tt> then an <tt>InetAddress</tt>
0N/A * representing an address of the loopback interface is returned.
0N/A * See <a href="http://www.ietf.org/rfc/rfc3330.txt">RFC&nbsp;3330</a>
0N/A * section&nbsp;2 and <a href="http://www.ietf.org/rfc/rfc2373.txt">RFC&nbsp;2373</a>
0N/A * section&nbsp;2.5.3. </p>
0N/A *
0N/A * @param host the specified host, or <code>null</code>.
0N/A * @return an IP address for the given host name.
0N/A * @exception UnknownHostException if no IP address for the
0N/A * <code>host</code> could be found, or if a scope_id was specified
0N/A * for a global IPv6 address.
0N/A * @exception SecurityException if a security manager exists
0N/A * and its checkConnect method doesn't allow the operation
0N/A */
0N/A public static InetAddress getByName(String host)
0N/A throws UnknownHostException {
0N/A return InetAddress.getAllByName(host)[0];
0N/A }
0N/A
4273N/A // called from deployment cache manager
4273N/A private static InetAddress getByName(String host, InetAddress reqAddr)
4273N/A throws UnknownHostException {
4273N/A return InetAddress.getAllByName(host, reqAddr)[0];
4273N/A }
4273N/A
0N/A /**
0N/A * Given the name of a host, returns an array of its IP addresses,
0N/A * based on the configured name service on the system.
0N/A *
0N/A * <p> The host name can either be a machine name, such as
0N/A * "<code>java.sun.com</code>", or a textual representation of its IP
0N/A * address. If a literal IP address is supplied, only the
0N/A * validity of the address format is checked.
0N/A *
0N/A * <p> For <code>host</code> specified in <i>literal IPv6 address</i>,
0N/A * either the form defined in RFC 2732 or the literal IPv6 address
0N/A * format defined in RFC 2373 is accepted. A literal IPv6 address may
0N/A * also be qualified by appending a scoped zone identifier or scope_id.
0N/A * The syntax and usage of scope_ids is described
0N/A * <a href="Inet6Address.html#scoped">here</a>.
0N/A * <p> If the host is <tt>null</tt> then an <tt>InetAddress</tt>
0N/A * representing an address of the loopback interface is returned.
0N/A * See <a href="http://www.ietf.org/rfc/rfc3330.txt">RFC&nbsp;3330</a>
0N/A * section&nbsp;2 and <a href="http://www.ietf.org/rfc/rfc2373.txt">RFC&nbsp;2373</a>
0N/A * section&nbsp;2.5.3. </p>
0N/A *
0N/A * <p> If there is a security manager and <code>host</code> is not
0N/A * null and <code>host.length() </code> is not equal to zero, the
0N/A * security manager's
0N/A * <code>checkConnect</code> method is called
0N/A * with the hostname and <code>-1</code>
0N/A * as its arguments to see if the operation is allowed.
0N/A *
0N/A * @param host the name of the host, or <code>null</code>.
0N/A * @return an array of all the IP addresses for a given host name.
0N/A *
0N/A * @exception UnknownHostException if no IP address for the
0N/A * <code>host</code> could be found, or if a scope_id was specified
0N/A * for a global IPv6 address.
0N/A * @exception SecurityException if a security manager exists and its
0N/A * <code>checkConnect</code> method doesn't allow the operation.
0N/A *
0N/A * @see SecurityManager#checkConnect
0N/A */
0N/A public static InetAddress[] getAllByName(String host)
0N/A throws UnknownHostException {
4273N/A return getAllByName(host, null);
4273N/A }
4273N/A
4273N/A private static InetAddress[] getAllByName(String host, InetAddress reqAddr)
4273N/A throws UnknownHostException {
0N/A
0N/A if (host == null || host.length() == 0) {
0N/A InetAddress[] ret = new InetAddress[1];
0N/A ret[0] = impl.loopbackAddress();
0N/A return ret;
0N/A }
0N/A
0N/A boolean ipv6Expected = false;
0N/A if (host.charAt(0) == '[') {
2801N/A // This is supposed to be an IPv6 literal
0N/A if (host.length() > 2 && host.charAt(host.length()-1) == ']') {
0N/A host = host.substring(1, host.length() -1);
0N/A ipv6Expected = true;
0N/A } else {
0N/A // This was supposed to be a IPv6 address, but it's not!
2801N/A throw new UnknownHostException(host + ": invalid IPv6 address");
0N/A }
0N/A }
0N/A
0N/A // if host is an IP address, we won't do further lookup
0N/A if (Character.digit(host.charAt(0), 16) != -1
0N/A || (host.charAt(0) == ':')) {
0N/A byte[] addr = null;
0N/A int numericZone = -1;
0N/A String ifname = null;
0N/A // see if it is IPv4 address
0N/A addr = IPAddressUtil.textToNumericFormatV4(host);
0N/A if (addr == null) {
0N/A // see if it is IPv6 address
0N/A // Check if a numeric or string zone id is present
0N/A int pos;
0N/A if ((pos=host.indexOf ("%")) != -1) {
0N/A numericZone = checkNumericZone (host);
0N/A if (numericZone == -1) { /* remainder of string must be an ifname */
0N/A ifname = host.substring (pos+1);
0N/A }
0N/A }
0N/A addr = IPAddressUtil.textToNumericFormatV6(host);
0N/A } else if (ipv6Expected) {
0N/A // Means an IPv4 litteral between brackets!
0N/A throw new UnknownHostException("["+host+"]");
0N/A }
0N/A InetAddress[] ret = new InetAddress[1];
0N/A if(addr != null) {
0N/A if (addr.length == Inet4Address.INADDRSZ) {
0N/A ret[0] = new Inet4Address(null, addr);
0N/A } else {
0N/A if (ifname != null) {
0N/A ret[0] = new Inet6Address(null, addr, ifname);
0N/A } else {
0N/A ret[0] = new Inet6Address(null, addr, numericZone);
0N/A }
0N/A }
0N/A return ret;
0N/A }
0N/A } else if (ipv6Expected) {
0N/A // We were expecting an IPv6 Litteral, but got something else
0N/A throw new UnknownHostException("["+host+"]");
0N/A }
4273N/A return getAllByName0(host, reqAddr, true);
0N/A }
0N/A
0N/A /**
0N/A * Returns the loopback address.
0N/A * <p>
0N/A * The InetAddress returned will represent the IPv4
0N/A * loopback address, 127.0.0.1, or the IPv6 loopback
0N/A * address, ::1. The IPv4 loopback address returned
0N/A * is only one of many in the form 127.*.*.*
0N/A *
0N/A * @return the InetAddress loopback instance.
0N/A * @since 1.7
0N/A */
0N/A public static InetAddress getLoopbackAddress() {
0N/A return impl.loopbackAddress();
0N/A }
0N/A
0N/A
0N/A /**
0N/A * check if the literal address string has %nn appended
0N/A * returns -1 if not, or the numeric value otherwise.
0N/A *
0N/A * %nn may also be a string that represents the displayName of
0N/A * a currently available NetworkInterface.
0N/A */
0N/A private static int checkNumericZone (String s) throws UnknownHostException {
0N/A int percent = s.indexOf ('%');
0N/A int slen = s.length();
0N/A int digit, zone=0;
0N/A if (percent == -1) {
0N/A return -1;
0N/A }
0N/A for (int i=percent+1; i<slen; i++) {
0N/A char c = s.charAt(i);
0N/A if (c == ']') {
0N/A if (i == percent+1) {
0N/A /* empty per-cent field */
0N/A return -1;
0N/A }
0N/A break;
0N/A }
0N/A if ((digit = Character.digit (c, 10)) < 0) {
0N/A return -1;
0N/A }
0N/A zone = (zone * 10) + digit;
0N/A }
0N/A return zone;
0N/A }
0N/A
0N/A private static InetAddress[] getAllByName0 (String host)
0N/A throws UnknownHostException
0N/A {
0N/A return getAllByName0(host, true);
0N/A }
0N/A
0N/A /**
0N/A * package private so SocketPermission can call it
0N/A */
0N/A static InetAddress[] getAllByName0 (String host, boolean check)
0N/A throws UnknownHostException {
4273N/A return getAllByName0 (host, null, check);
4273N/A }
4273N/A
4273N/A private static InetAddress[] getAllByName0 (String host, InetAddress reqAddr, boolean check)
4273N/A throws UnknownHostException {
4273N/A
0N/A /* If it gets here it is presumed to be a hostname */
0N/A /* Cache.get can return: null, unknownAddress, or InetAddress[] */
0N/A
0N/A /* make sure the connection to the host is allowed, before we
0N/A * give out a hostname
0N/A */
0N/A if (check) {
0N/A SecurityManager security = System.getSecurityManager();
0N/A if (security != null) {
0N/A security.checkConnect(host, -1);
0N/A }
0N/A }
0N/A
2801N/A InetAddress[] addresses = getCachedAddresses(host);
0N/A
0N/A /* If no entry in cache, then do the host lookup */
2801N/A if (addresses == null) {
4273N/A addresses = getAddressesFromNameService(host, reqAddr);
0N/A }
0N/A
2801N/A if (addresses == unknown_array)
0N/A throw new UnknownHostException(host);
0N/A
2801N/A return addresses.clone();
0N/A }
0N/A
4273N/A private static InetAddress[] getAddressesFromNameService(String host, InetAddress reqAddr)
0N/A throws UnknownHostException
0N/A {
2801N/A InetAddress[] addresses = null;
0N/A boolean success = false;
0N/A UnknownHostException ex = null;
0N/A
0N/A // Check whether the host is in the lookupTable.
0N/A // 1) If the host isn't in the lookupTable when
0N/A // checkLookupTable() is called, checkLookupTable()
0N/A // would add the host in the lookupTable and
0N/A // return null. So we will do the lookup.
0N/A // 2) If the host is in the lookupTable when
0N/A // checkLookupTable() is called, the current thread
0N/A // would be blocked until the host is removed
0N/A // from the lookupTable. Then this thread
0N/A // should try to look up the addressCache.
2801N/A // i) if it found the addresses in the
0N/A // addressCache, checkLookupTable() would
2801N/A // return the addresses.
2801N/A // ii) if it didn't find the addresses in the
0N/A // addressCache for any reason,
0N/A // it should add the host in the
0N/A // lookupTable and return null so the
0N/A // following code would do a lookup itself.
2801N/A if ((addresses = checkLookupTable(host)) == null) {
3406N/A try {
3406N/A // This is the first thread which looks up the addresses
3406N/A // this host or the cache entry for this host has been
3406N/A // expired so this thread should do the lookup.
3406N/A for (NameService nameService : nameServices) {
3406N/A try {
3406N/A /*
3406N/A * Do not put the call to lookup() inside the
3406N/A * constructor. if you do you will still be
3406N/A * allocating space when the lookup fails.
3406N/A */
0N/A
3406N/A addresses = nameService.lookupAllHostAddr(host);
0N/A success = true;
0N/A break;
3406N/A } catch (UnknownHostException uhe) {
3406N/A if (host.equalsIgnoreCase("localhost")) {
3406N/A InetAddress[] local = new InetAddress[] { impl.loopbackAddress() };
3406N/A addresses = local;
3406N/A success = true;
3406N/A break;
3406N/A }
3406N/A else {
3406N/A addresses = unknown_array;
3406N/A success = false;
3406N/A ex = uhe;
3406N/A }
0N/A }
0N/A }
3406N/A
4273N/A // More to do?
4273N/A if (reqAddr != null && addresses.length > 1 && !addresses[0].equals(reqAddr)) {
4273N/A // Find it?
4273N/A int i = 1;
4273N/A for (; i < addresses.length; i++) {
4273N/A if (addresses[i].equals(reqAddr)) {
4273N/A break;
4273N/A }
4273N/A }
4273N/A // Rotate
4273N/A if (i < addresses.length) {
4273N/A InetAddress tmp, tmp2 = reqAddr;
4273N/A for (int j = 0; j < i; j++) {
4273N/A tmp = addresses[j];
4273N/A addresses[j] = tmp2;
4273N/A tmp2 = tmp;
4273N/A }
4273N/A addresses[i] = tmp2;
4273N/A }
4273N/A }
4273N/A // Cache the address.
3406N/A cacheAddresses(host, addresses, success);
4273N/A
3406N/A if (!success && ex != null)
3406N/A throw ex;
4273N/A
3406N/A } finally {
3406N/A // Delete host from the lookupTable and notify
3406N/A // all threads waiting on the lookupTable monitor.
3406N/A updateLookupTable(host);
0N/A }
0N/A }
0N/A
2801N/A return addresses;
0N/A }
0N/A
0N/A
2801N/A private static InetAddress[] checkLookupTable(String host) {
0N/A synchronized (lookupTable) {
0N/A // If the host isn't in the lookupTable, add it in the
0N/A // lookuptable and return null. The caller should do
0N/A // the lookup.
0N/A if (lookupTable.containsKey(host) == false) {
0N/A lookupTable.put(host, null);
3406N/A return null;
0N/A }
0N/A
0N/A // If the host is in the lookupTable, it means that another
2801N/A // thread is trying to look up the addresses of this host.
0N/A // This thread should wait.
0N/A while (lookupTable.containsKey(host)) {
0N/A try {
0N/A lookupTable.wait();
0N/A } catch (InterruptedException e) {
0N/A }
0N/A }
0N/A }
0N/A
2801N/A // The other thread has finished looking up the addresses of
2801N/A // the host. This thread should retry to get the addresses
2801N/A // from the addressCache. If it doesn't get the addresses from
2801N/A // the cache, it will try to look up the addresses itself.
3406N/A InetAddress[] addresses = getCachedAddresses(host);
2801N/A if (addresses == null) {
0N/A synchronized (lookupTable) {
0N/A lookupTable.put(host, null);
3406N/A return null;
0N/A }
0N/A }
0N/A
2801N/A return addresses;
0N/A }
0N/A
0N/A private static void updateLookupTable(String host) {
0N/A synchronized (lookupTable) {
0N/A lookupTable.remove(host);
0N/A lookupTable.notifyAll();
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Returns an <code>InetAddress</code> object given the raw IP address .
0N/A * The argument is in network byte order: the highest order
0N/A * byte of the address is in <code>getAddress()[0]</code>.
0N/A *
0N/A * <p> This method doesn't block, i.e. no reverse name service lookup
0N/A * is performed.
0N/A *
0N/A * <p> IPv4 address byte array must be 4 bytes long and IPv6 byte array
0N/A * must be 16 bytes long
0N/A *
0N/A * @param addr the raw IP address in network byte order
0N/A * @return an InetAddress object created from the raw IP address.
0N/A * @exception UnknownHostException if IP address is of illegal length
0N/A * @since 1.4
0N/A */
0N/A public static InetAddress getByAddress(byte[] addr)
0N/A throws UnknownHostException {
0N/A return getByAddress(null, addr);
0N/A }
0N/A
0N/A private static InetAddress cachedLocalHost = null;
0N/A private static long cacheTime = 0;
0N/A private static final long maxCacheTime = 5000L;
0N/A private static final Object cacheLock = new Object();
0N/A
0N/A /**
0N/A * Returns the address of the local host. This is achieved by retrieving
0N/A * the name of the host from the system, then resolving that name into
0N/A * an <code>InetAddress</code>.
0N/A *
0N/A * <P>Note: The resolved address may be cached for a short period of time.
0N/A * </P>
0N/A *
0N/A * <p>If there is a security manager, its
0N/A * <code>checkConnect</code> method is called
0N/A * with the local host name and <code>-1</code>
0N/A * as its arguments to see if the operation is allowed.
0N/A * If the operation is not allowed, an InetAddress representing
0N/A * the loopback address is returned.
0N/A *
0N/A * @return the address of the local host.
0N/A *
0N/A * @exception UnknownHostException if the local host name could not
0N/A * be resolved into an address.
0N/A *
0N/A * @see SecurityManager#checkConnect
0N/A * @see java.net.InetAddress#getByName(java.lang.String)
0N/A */
0N/A public static InetAddress getLocalHost() throws UnknownHostException {
0N/A
0N/A SecurityManager security = System.getSecurityManager();
0N/A try {
0N/A String local = impl.getLocalHostName();
0N/A
0N/A if (security != null) {
0N/A security.checkConnect(local, -1);
0N/A }
0N/A
0N/A if (local.equals("localhost")) {
0N/A return impl.loopbackAddress();
0N/A }
0N/A
0N/A InetAddress ret = null;
0N/A synchronized (cacheLock) {
0N/A long now = System.currentTimeMillis();
0N/A if (cachedLocalHost != null) {
0N/A if ((now - cacheTime) < maxCacheTime) // Less than 5s old?
0N/A ret = cachedLocalHost;
0N/A else
0N/A cachedLocalHost = null;
0N/A }
0N/A
2801N/A // we are calling getAddressesFromNameService directly
0N/A // to avoid getting localHost from cache
0N/A if (ret == null) {
0N/A InetAddress[] localAddrs;
0N/A try {
0N/A localAddrs =
4273N/A InetAddress.getAddressesFromNameService(local, null);
0N/A } catch (UnknownHostException uhe) {
2801N/A // Rethrow with a more informative error message.
2801N/A UnknownHostException uhe2 =
2801N/A new UnknownHostException(local + ": " +
2801N/A uhe.getMessage());
2801N/A uhe2.initCause(uhe);
2801N/A throw uhe2;
0N/A }
0N/A cachedLocalHost = localAddrs[0];
0N/A cacheTime = now;
0N/A ret = localAddrs[0];
0N/A }
0N/A }
0N/A return ret;
0N/A } catch (java.lang.SecurityException e) {
0N/A return impl.loopbackAddress();
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Perform class load-time initializations.
0N/A */
0N/A private static native void init();
0N/A
0N/A
0N/A /*
0N/A * Returns the InetAddress representing anyLocalAddress
0N/A * (typically 0.0.0.0 or ::0)
0N/A */
0N/A static InetAddress anyLocalAddress() {
0N/A return impl.anyLocalAddress();
0N/A }
0N/A
0N/A /*
0N/A * Load and instantiate an underlying impl class
0N/A */
2801N/A static InetAddressImpl loadImpl(String implName) {
2801N/A Object impl = null;
0N/A
0N/A /*
0N/A * Property "impl.prefix" will be prepended to the classname
0N/A * of the implementation object we instantiate, to which we
0N/A * delegate the real work (like native methods). This
0N/A * property can vary across implementations of the java.
0N/A * classes. The default is an empty String "".
0N/A */
0N/A String prefix = AccessController.doPrivileged(
0N/A new GetPropertyAction("impl.prefix", ""));
0N/A try {
0N/A impl = Class.forName("java.net." + prefix + implName).newInstance();
0N/A } catch (ClassNotFoundException e) {
0N/A System.err.println("Class not found: java.net." + prefix +
0N/A implName + ":\ncheck impl.prefix property " +
0N/A "in your properties file.");
0N/A } catch (InstantiationException e) {
0N/A System.err.println("Could not instantiate: java.net." + prefix +
0N/A implName + ":\ncheck impl.prefix property " +
0N/A "in your properties file.");
0N/A } catch (IllegalAccessException e) {
0N/A System.err.println("Cannot access class: java.net." + prefix +
0N/A implName + ":\ncheck impl.prefix property " +
0N/A "in your properties file.");
0N/A }
0N/A
0N/A if (impl == null) {
0N/A try {
0N/A impl = Class.forName(implName).newInstance();
0N/A } catch (Exception e) {
0N/A throw new Error("System property impl.prefix incorrect");
0N/A }
0N/A }
0N/A
2801N/A return (InetAddressImpl) impl;
0N/A }
2259N/A
2259N/A private void readObjectNoData (ObjectInputStream s) throws
2259N/A IOException, ClassNotFoundException {
2259N/A if (getClass().getClassLoader() != null) {
2259N/A throw new SecurityException ("invalid address type");
2259N/A }
2259N/A }
2259N/A
5888N/A private static final long FIELDS_OFFSET;
5888N/A private static final sun.misc.Unsafe UNSAFE;
5888N/A
5888N/A static {
5888N/A try {
5888N/A sun.misc.Unsafe unsafe = sun.misc.Unsafe.getUnsafe();
5888N/A FIELDS_OFFSET = unsafe.objectFieldOffset(
5888N/A InetAddress.class.getDeclaredField("holder")
5888N/A );
5888N/A UNSAFE = unsafe;
5888N/A } catch (ReflectiveOperationException e) {
5888N/A throw new Error(e);
5888N/A }
5888N/A }
5888N/A
2259N/A private void readObject (ObjectInputStream s) throws
2259N/A IOException, ClassNotFoundException {
2259N/A if (getClass().getClassLoader() != null) {
2259N/A throw new SecurityException ("invalid address type");
2259N/A }
5888N/A GetField gf = s.readFields();
5888N/A String host = (String)gf.get("hostName", null);
5888N/A int address= gf.get("address", 0);
5888N/A int family= gf.get("family", 0);
5888N/A InetAddressHolder h = new InetAddressHolder(host, address, family);
5888N/A UNSAFE.putObject(this, FIELDS_OFFSET, h);
5888N/A }
5888N/A
5888N/A /* needed because the serializable fields no longer exist */
5888N/A
5888N/A /**
5888N/A * @serialField hostName String
5888N/A * @serialField address int
5888N/A * @serialField family int
5888N/A */
5888N/A private static final ObjectStreamField[] serialPersistentFields = {
5888N/A new ObjectStreamField("hostName", String.class),
5888N/A new ObjectStreamField("address", int.class),
5888N/A new ObjectStreamField("family", int.class),
5888N/A };
5888N/A
5888N/A private void writeObject (ObjectOutputStream s) throws
5888N/A IOException {
5888N/A if (getClass().getClassLoader() != null) {
5888N/A throw new SecurityException ("invalid address type");
5888N/A }
5888N/A PutField pf = s.putFields();
5888N/A pf.put("hostName", holder().hostName);
5888N/A pf.put("address", holder().address);
5888N/A pf.put("family", holder().family);
5888N/A s.writeFields();
5888N/A s.flush();
2259N/A }
0N/A}
0N/A
0N/A/*
0N/A * Simple factory to create the impl
0N/A */
0N/Aclass InetAddressImplFactory {
0N/A
0N/A static InetAddressImpl create() {
2801N/A return InetAddress.loadImpl(isIPv6Supported() ?
2801N/A "Inet6AddressImpl" : "Inet4AddressImpl");
0N/A }
0N/A
0N/A static native boolean isIPv6Supported();
0N/A}