InetAddress.java revision 0
2362N/A * Copyright 1995-2007 Sun Microsystems, Inc. All Rights Reserved. 0N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 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. Sun designates this 0N/A * particular file as subject to the "Classpath" exception as provided 2362N/A * by Sun in the LICENSE file that accompanied this code. 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 * 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. 2362N/A * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, 2362N/A * CA 95054 USA or visit www.sun.com if you need additional information or 0N/A * This class represents an Internet Protocol (IP) address. 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 * Assigned Numbers</i></a>, <a 0N/A * Address Allocation for Private Internets</i></a>, <a 0N/A * Administratively Scoped IP Multicast</i></a>, and <a 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 * <h4> Address types </h4> 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 * <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 * <p> The <i>unspecified</i> address must not be used as 0N/A * the destination address of an IP packet. 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 * <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 * <h4> IP address scope </h4> 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 * <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 * <p> <i>Global</i> addresses are unique across the internet. 0N/A * <h4> Textual representation of IP addresses </h4> 0N/A * The textual representation of an IP address is address family specific. 0N/A * For IPv4 address format, please refer to <A 0N/A * address format, please refer to <A 0N/A * System Properties</a> affecting how IPv4 and IPv6 addresses are used.</P> 0N/A * <h4> Host Name Resolution </h4> 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 * <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 * <p> The InetAddress class provides methods to resolve host names to 0N/A * their IP addresses and vice versa. 0N/A * <h4> InetAddress Caching </h4> 0N/A * The InetAddress class has a cache to store successful as well as 0N/A * unsuccessful host name resolutions. 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 * <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 * <p> Two Java security properties control the TTL values used for 0N/A * positive and negative host name resolution caching: 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 * A value of -1 indicates "cache forever". 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 * A value of 0 indicates "never cache". 0N/A * A value of -1 indicates "cache forever". 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 * Specify the address family: Internet Protocol, Version 4 0N/A * Specify the address family: Internet Protocol, Version 6 0N/A /* Specify address family preference */ 0N/A * Holds a 32-bit IPv4 address. 0N/A * Specifies the address family type, for instance, '1' for IPv4 0N/A * addresses, and '2' for IPv6 addresses. 0N/A /* Used to store the name service provider */ 0N/A /* Used to store the best available hostname */ 0N/A /** use serialVersionUID from JDK 1.0.2 for interoperability */ 0N/A * Load net library into runtime, and perform initializations. 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 * Replaces the de-serialized object with an Inet4Address object. 0N/A * @return the alternate object to the de-serialized object. 0N/A * @throws ObjectStreamException if a new object replacing this 0N/A * object could not be created 0N/A // will replace the deserialized 'this' object 0N/A * Utility routine to check if the InetAddress is an * @return a <code>boolean</code> indicating if the InetAddress is * an IP multicast address * Utility routine to check if the InetAddress in a wildcard address. * @return a <code>boolean</code> indicating if the Inetaddress is * Utility routine to check if the InetAddress is a loopback address. * @return a <code>boolean</code> indicating if the InetAddress is * a loopback address; or false otherwise. * Utility routine to check if the InetAddress is an link local address. * @return a <code>boolean</code> indicating if the InetAddress is * a link local address; or false if address is not a link local unicast address. * Utility routine to check if the InetAddress is a site local address. * @return a <code>boolean</code> indicating if the InetAddress is * a site local address; or false if address is not a site local unicast address. * Utility routine to check if the multicast address has global scope. * @return a <code>boolean</code> indicating if the address has * is a multicast address of global scope, false if it is not * of global scope or it is not a multicast address * Utility routine to check if the multicast address has node scope. * @return a <code>boolean</code> indicating if the address has * is a multicast address of node-local scope, false if it is not * of node-local scope or it is not a multicast address * Utility routine to check if the multicast address has link scope. * @return a <code>boolean</code> indicating if the address has * is a multicast address of link-local scope, false if it is not * of link-local scope or it is not a multicast address * Utility routine to check if the multicast address has site scope. * @return a <code>boolean</code> indicating if the address has * is a multicast address of site-local scope, false if it is not * of site-local scope or it is not a multicast address * Utility routine to check if the multicast address has organization scope. * @return a <code>boolean</code> indicating if the address has * is a multicast address of organization-local scope, * false if it is not of organization-local scope * or it is not a multicast address * Test whether that address is reachable. Best effort is made by the * implementation to try to reach the host, but firewalls and server * configuration may block requests resulting in a unreachable status * while some specific ports may be accessible. * A typical implementation will use ICMP ECHO REQUESTs if the * privilege can be obtained, otherwise it will try to establish * a TCP connection on port 7 (Echo) of the destination host. * The timeout value, in milliseconds, indicates the maximum amount of time * the try should take. If the operation times out before getting an * answer, the host is deemed unreachable. A negative value will result * in an IllegalArgumentException being thrown. * @param timeout the time, in milliseconds, before the call aborts * @return a <code>boolean</code> indicating if the address is reachable. * @throws IOException if a network error occurs * @throws IllegalArgumentException if <code>timeout</code> is negative. * Test whether that address is reachable. Best effort is made by the * implementation to try to reach the host, but firewalls and server * configuration may block requests resulting in a unreachable status * while some specific ports may be accessible. * A typical implementation will use ICMP ECHO REQUESTs if the * privilege can be obtained, otherwise it will try to establish * a TCP connection on port 7 (Echo) of the destination host. * The <code>network interface</code> and <code>ttl</code> parameters * let the caller specify which network interface the test will go through * and the maximum number of hops the packets should go through. * A negative value for the <code>ttl</code> will result in an * IllegalArgumentException being thrown. * The timeout value, in milliseconds, indicates the maximum amount of time * the try should take. If the operation times out before getting an * answer, the host is deemed unreachable. A negative value will result * in an IllegalArgumentException being thrown. * @param netif the NetworkInterface through which the * test will be done, or null for any interface * @param ttl the maximum numbers of hops to try or 0 for the * @param timeout the time, in milliseconds, before the call aborts * @throws IllegalArgumentException if either <code>timeout</code> * or <code>ttl</code> are negative. * @return a <code>boolean</code>indicating if the address is reachable. * @throws IOException if a network error occurs * Gets the host name for this IP address. * <p>If this InetAddress was created with a host name, * this host name will be remembered and returned; * otherwise, a reverse name lookup will be performed * and the result will be returned based on the system * configured name lookup service. If a lookup of the name service * {@link #getCanonicalHostName() getCanonicalHostName}. * <p>If there is a security manager, its * <code>checkConnect</code> method is first called * with the hostname and <code>-1</code> * as its arguments to see if the operation is allowed. * If the operation is not allowed, it will return * the textual representation of the IP address. * @return the host name for this IP address, or if the operation * is not allowed by the security check, the textual * representation of the IP address. * @see InetAddress#getCanonicalHostName * @see SecurityManager#checkConnect * Returns the hostname for this address. * If the host is equal to null, then this address refers to any * of the local machine's available network addresses. * this is package private so SocketPermission can make calls into * here without a security check. * <p>If there is a security manager, this method first * calls its <code>checkConnect</code> method * with the hostname and <code>-1</code> * as its arguments to see if the calling code is allowed to know * the hostname for this IP address, i.e., to connect to the host. * If the operation is not allowed, it will return * the textual representation of the IP address. * @return the host name for this IP address, or if the operation * is not allowed by the security check, the textual * representation of the IP address. * @param check make security check if true * @see SecurityManager#checkConnect * Gets the fully qualified domain name for this IP address. * Best effort method, meaning we may not be able to return * the FQDN depending on the underlying system configuration. * <p>If there is a security manager, this method first * calls its <code>checkConnect</code> method * with the hostname and <code>-1</code> * as its arguments to see if the calling code is allowed to know * the hostname for this IP address, i.e., to connect to the host. * If the operation is not allowed, it will return * the textual representation of the IP address. * @return the fully qualified domain name for this IP address, * or if the operation is not allowed by the security check, * the textual representation of the IP address. * @see SecurityManager#checkConnect * Returns the hostname for this address. * <p>If there is a security manager, this method first * calls its <code>checkConnect</code> method * with the hostname and <code>-1</code> * as its arguments to see if the calling code is allowed to know * the hostname for this IP address, i.e., to connect to the host. * If the operation is not allowed, it will return * the textual representation of the IP address. * @return the host name for this IP address, or if the operation * is not allowed by the security check, the textual * representation of the IP address. * @param check make security check if true * @see SecurityManager#checkConnect // first lookup the hostname /* check to see if calling code is allowed to know * the hostname for this IP address, ie, connect to the host /* now get all the IP addresses for this hostname, * and make sure one of them matches the original IP * address. We do this to try and prevent spoofing. //XXX: if it looks a spoof just return the address? // let next provider resolve the hostname * Returns the raw IP address of this <code>InetAddress</code> * object. The result is in network byte order: the highest order * byte of the address is in <code>getAddress()[0]</code>. * @return the raw IP address of this object. * Returns the IP address string in textual presentation. * @return the raw IP address in a string format. * Returns a hashcode for this IP address. * @return a hash code value for this IP address. * Compares this object against the specified object. * The result is <code>true</code> if and only if the argument is * not <code>null</code> and it represents the same IP address as * Two instances of <code>InetAddress</code> represent the same IP * address if the length of the byte arrays returned by * <code>getAddress</code> is the same for both, and each of the * array components is the same for the byte arrays. * @param obj the object to compare against. * @return <code>true</code> if the objects are the same; * <code>false</code> otherwise. * @see java.net.InetAddress#getAddress() * Converts this IP address to a <code>String</code>. The * string returned is of the form: hostname / literal IP * If the host name is unresolved, no reverse name service lookup * is performed. The hostname part will be represented by an empty string. * @return a string representation of this IP address. * Cached addresses - our own litle nis, not! * Represents a cache entry * A cache that manages entries based on a policy specified static final class Cache {
* Add an entry to the cache. If there's already an * entry then for this host then the entry will be // purge any expired entries // As we iterate in insertion order we can // terminate when a non-expired entry is found. // create new entry and add it to the cache // -- as a HashMap replaces existing entries we // don't need to explicitly check if there is // already an entry for this host. * Query the cache for the specific host. If found then * return its CacheEntry, or null if not found. // check if entry has expired * Initialize cache and insert anyLocalAddress into the * unknown array with no expiry. * Cache the given hostname and address. * Lookup hostname in cache (positive & negative cache). If * found return address, null if not found. // search both positive & negative caches // initialize the default name service "Cannot create name service:" // get name service if provided and requested // if not designate any name services provider, * Create an InetAddress based on the provided host name and IP address * No name service is checked for the validity of the address. * <p> The host name can either be a machine name, such as * "<code>java.sun.com</code>", or a textual representation of its IP * <p> No validity checking is done on the host name either. * <p> If addr specifies an IPv4 address an instance of Inet4Address * will be returned; otherwise, an instance of Inet6Address * <p> IPv4 address byte array must be 4 bytes long and IPv6 byte array * @param host the specified host * @param addr the raw IP address in network byte order * @return an InetAddress object created from the raw IP address. * @exception UnknownHostException if IP address is of illegal length * Determines the IP address of a host, given the host's name. * <p> The host name can either be a machine name, such as * "<code>java.sun.com</code>", or a textual representation of its * IP address. If a literal IP address is supplied, only the * validity of the address format is checked. * <p> For <code>host</code> specified in literal IPv6 address, * either the form defined in RFC 2732 or the literal IPv6 address * format defined in RFC 2373 is accepted. IPv6 scoped addresses are also * supported. See <a href="Inet6Address.html#scoped">here</a> for a description of IPv6 * <p> If the host is <tt>null</tt> then an <tt>InetAddress</tt> * representing an address of the loopback interface is returned. * section 2.5.3. </p> * @param host the specified host, or <code>null</code>. * @return an IP address for the given host name. * @exception UnknownHostException if no IP address for the * <code>host</code> could be found, or if a scope_id was specified * for a global IPv6 address. * @exception SecurityException if a security manager exists * and its checkConnect method doesn't allow the operation * Given the name of a host, returns an array of its IP addresses, * based on the configured name service on the system. * <p> The host name can either be a machine name, such as * "<code>java.sun.com</code>", or a textual representation of its IP * address. If a literal IP address is supplied, only the * validity of the address format is checked. * <p> For <code>host</code> specified in <i>literal IPv6 address</i>, * either the form defined in RFC 2732 or the literal IPv6 address * format defined in RFC 2373 is accepted. A literal IPv6 address may * also be qualified by appending a scoped zone identifier or scope_id. * The syntax and usage of scope_ids is described * <p> If the host is <tt>null</tt> then an <tt>InetAddress</tt> * representing an address of the loopback interface is returned. * section 2.5.3. </p> * <p> If there is a security manager and <code>host</code> is not * null and <code>host.length() </code> is not equal to zero, the * <code>checkConnect</code> method is called * with the hostname and <code>-1</code> * as its arguments to see if the operation is allowed. * @param host the name of the host, or <code>null</code>. * @return an array of all the IP addresses for a given host name. * @exception UnknownHostException if no IP address for the * <code>host</code> could be found, or if a scope_id was specified * for a global IPv6 address. * @exception SecurityException if a security manager exists and its * <code>checkConnect</code> method doesn't allow the operation. * @see SecurityManager#checkConnect // This is supposed to be an IPv6 litteral // This was supposed to be a IPv6 address, but it's not! // if host is an IP address, we won't do further lookup // see if it is IPv4 address // see if it is IPv6 address // Check if a numeric or string zone id is present if (
numericZone == -
1) {
/* remainder of string must be an ifname */ // Means an IPv4 litteral between brackets! // We were expecting an IPv6 Litteral, but got something else * Returns the loopback address. * The InetAddress returned will represent the IPv4 * loopback address, 127.0.0.1, or the IPv6 loopback * address, ::1. The IPv4 loopback address returned * is only one of many in the form 127.*.*.* * @return the InetAddress loopback instance. * check if the literal address string has %nn appended * returns -1 if not, or the numeric value otherwise. * %nn may also be a string that represents the displayName of * a currently available NetworkInterface. /* empty per-cent field */ * package private so SocketPermission can call it /* If it gets here it is presumed to be a hostname */ /* Cache.get can return: null, unknownAddress, or InetAddress[] */ /* make sure the connection to the host is allowed, before we /* If no entry in cache, then do the host lookup */ /* Make a copy of the InetAddress array */ // Check whether the host is in the lookupTable. // 1) If the host isn't in the lookupTable when // checkLookupTable() is called, checkLookupTable() // would add the host in the lookupTable and // return null. So we will do the lookup. // 2) If the host is in the lookupTable when // checkLookupTable() is called, the current thread // would be blocked until the host is removed // from the lookupTable. Then this thread // should try to look up the addressCache. // i) if it found the address in the // addressCache, checkLookupTable() would // ii) if it didn't find the address in the // addressCache for any reason, // it should add the host in the // lookupTable and return null so the // following code would do a lookup itself. // This is the first thread which looks up the address // this host or the cache entry for this host has been // expired so this thread should do the lookup. * Do not put the call to lookup() inside the * constructor. if you do you will still be * allocating space when the lookup fails. // Delete the host from the lookupTable, and // notify all threads waiting for the monitor // make sure obj is null. // If the host isn't in the lookupTable, add it in the // lookuptable and return null. The caller should do // If the host is in the lookupTable, it means that another // thread is trying to look up the address of this host. // This thread should wait. // The other thread has finished looking up the address of // the host. This thread should retry to get the address // from the addressCache. If it doesn't get the address from // the cache, it will try to look up the address itself. * Returns an <code>InetAddress</code> object given the raw IP address . * The argument is in network byte order: the highest order * byte of the address is in <code>getAddress()[0]</code>. * <p> This method doesn't block, i.e. no reverse name service lookup * <p> IPv4 address byte array must be 4 bytes long and IPv6 byte array * @param addr the raw IP address in network byte order * @return an InetAddress object created from the raw IP address. * @exception UnknownHostException if IP address is of illegal length * Returns the address of the local host. This is achieved by retrieving * the name of the host from the system, then resolving that name into * an <code>InetAddress</code>. * <P>Note: The resolved address may be cached for a short period of time. * <p>If there is a security manager, its * <code>checkConnect</code> method is called * with the local host name and <code>-1</code> * as its arguments to see if the operation is allowed. * If the operation is not allowed, an InetAddress representing * the loopback address is returned. * @return the address of the local host. * @exception UnknownHostException if the local host name could not * be resolved into an address. * @see SecurityManager#checkConnect * @see java.net.InetAddress#getByName(java.lang.String) // we are calling getAddressFromNameService directly // to avoid getting localHost from cache * Perform class load-time initializations. private static native void init();
* Returns the InetAddress representing anyLocalAddress * (typically 0.0.0.0 or ::0) * Load and instantiate an underlying impl class * Property "impl.prefix" will be prepended to the classname * of the implementation object we instantiate, to which we * delegate the real work (like native methods). This * property can vary across implementations of the java. * classes. The default is an empty String "". implName +
":\ncheck impl.prefix property " +
"in your properties file.");
implName +
":\ncheck impl.prefix property " +
"in your properties file.");
implName +
":\ncheck impl.prefix property " +
"in your properties file.");
throw new Error(
"System property impl.prefix incorrect");
* Simple factory to create the impl