KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > java > net > InetAddress


1 /*
2  * @(#)InetAddress.java 1.116 07/09/05
3  *
4  * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
5  * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6  */

7
8 package java.net;
9
10 import java.util.HashMap JavaDoc;
11 import java.util.LinkedHashMap JavaDoc;
12 import java.util.Random JavaDoc;
13 import java.util.Iterator JavaDoc;
14 import java.util.LinkedList JavaDoc;
15 import java.security.AccessController JavaDoc;
16 import java.io.ObjectStreamException JavaDoc;
17 import java.io.IOException JavaDoc;
18 import sun.security.action.*;
19 import sun.net.InetAddressCachePolicy;
20 import sun.net.util.IPAddressUtil;
21 import sun.misc.Service;
22 import sun.net.spi.nameservice.*;
23
24 /**
25  * This class represents an Internet Protocol (IP) address.
26  *
27  * <p> An IP address is either a 32-bit or 128-bit unsigned number
28  * used by IP, a lower-level protocol on which protocols like UDP and
29  * TCP are built. The IP address architecture is defined by <a
30  * HREF="http://www.ietf.org/rfc/rfc790.txt"><i>RFC&nbsp;790:
31  * Assigned Numbers</i></a>, <a
32  * HREF="http://www.ietf.org/rfc/rfc1918.txt"> <i>RFC&nbsp;1918:
33  * Address Allocation for Private Internets</i></a>, <a
34  * HREF="http://www.ietf.org/rfc/rfc2365.txt"><i>RFC&nbsp;2365:
35  * Administratively Scoped IP Multicast</i></a>, and <a
36  * HREF="http://www.ietf.org/rfc/rfc2373.txt"><i>RFC&nbsp;2373: IP
37  * Version 6 Addressing Architecture</i></a>. An instance of an
38  * InetAddress consists of an IP address and possibly its
39  * corresponding host name (depending on whether it is constructed
40  * with a host name or whether it has already done reverse host name
41  * resolution).
42  *
43  * <h4> Address types </h4>
44  *
45  * <blockquote><table cellspacing=2 summary="Description of unicast and multicast address types">
46  * <tr><th valign=top><i>unicast</i></th>
47  * <td>An identifier for a single interface. A packet sent to
48  * a unicast address is delivered to the interface identified by
49  * that address.
50  *
51  * <p> The Unspecified Address -- Also called anylocal or wildcard
52  * address. It must never be assigned to any node. It indicates the
53  * absence of an address. One example of its use is as the target of
54  * bind, which allows a server to accept a client connection on any
55  * interface, in case the server host has multiple interfaces.
56  *
57  * <p> The <i>unspecified</i> address must not be used as
58  * the destination address of an IP packet.
59  *
60  * <p> The <i>Loopback</i> Addresses -- This is the address
61  * assigned to the loopback interface. Anything sent to this
62  * IP address loops around and becomes IP input on the local
63  * host. This address is often used when testing a
64  * client.</td></tr>
65  * <tr><th valign=top><i>multicast</i></th>
66  * <td>An identifier for a set of interfaces (typically belonging
67  * to different nodes). A packet sent to a multicast address is
68  * delivered to all interfaces identified by that address.</td></tr>
69  * </table></blockquote>
70  *
71  * <h4> IP address scope </h4>
72  *
73  * <p> <i>Link-local</i> addresses are designed to be used for addressing
74  * on a single link for purposes such as auto-address configuration,
75  * neighbor discovery, or when no routers are present.
76  *
77  * <p> <i>Site-local</i> addresses are designed to be used for addressing
78  * inside of a site without the need for a global prefix.
79  *
80  * <p> <i>Global</i> addresses are unique across the internet.
81  *
82  * <h4> Textual representation of IP addresses </h4>
83  *
84  * The textual representation of an IP address is address family specific.
85  *
86  * <p>
87  *
88  * For IPv4 address format, please refer to <A
89  * HREF="Inet4Address.html#format">Inet4Address#format</A>; For IPv6
90  * address format, please refer to <A
91  * HREF="Inet6Address.html#format">Inet6Address#format</A>.
92  *
93  * <h4> Host Name Resolution </h4>
94  *
95  * Host name-to-IP address <i>resolution</i> is accomplished through
96  * the use of a combination of local machine configuration information
97  * and network naming services such as the Domain Name System (DNS)
98  * and Network Information Service(NIS). The particular naming
99  * services(s) being used is by default the local machine configured
100  * one. For any host name, its corresponding IP address is returned.
101  *
102  * <p> <i>Reverse name resolution</i> means that for any IP address,
103  * the host associated with the IP address is returned.
104  *
105  * <p> The InetAddress class provides methods to resolve host names to
106  * their IP addresses and vice versa.
107  *
108  * <h4> InetAddress Caching </h4>
109  *
110  * The InetAddress class has a cache to store successful as well as
111  * unsuccessful host name resolutions.
112  *
113  * <p> By default, when a security manager is installed, in order to
114  * protect against DNS spoofing attacks,
115  * the result of positive host name resolutions are
116  * cached forever. When a security manager is not installed, the default
117  * behavior is to cache entries for a finite (implementation dependent)
118  * period of time. The result of unsuccessful host
119  * name resolution is cached for a very short period of time (10
120  * seconds) to improve performance.
121  *
122  * <p> If the default behavior is not desired, then a Java security property
123  * can be set to a different Time-to-live (TTL) value for positive
124  * caching. Likewise, a system admin can configure a different
125  * negative caching TTL value when needed.
126  *
127  * <p> Two Java security properties control the TTL values used for
128  * positive and negative host name resolution caching:
129  *
130  * <blockquote>
131  * <dl>
132  * <dt><b>networkaddress.cache.ttl</b></dt>
133  * <dd>Indicates the caching policy for successful name lookups from
134  * the name service. The value is specified as as integer to indicate
135  * the number of seconds to cache the successful lookup. The default
136  * setting is to cache for an implementation specific period of time.
137  * <p>
138  * A value of -1 indicates "cache forever".
139  * </dd>
140  * <p>
141  * <dt><b>networkaddress.cache.negative.ttl</b> (default: 10)</dt>
142  * <dd>Indicates the caching policy for un-successful name lookups
143  * from the name service. The value is specified as as integer to
144  * indicate the number of seconds to cache the failure for
145  * un-successful lookups.
146  * <p>
147  * A value of 0 indicates "never cache".
148  * A value of -1 indicates "cache forever".
149  * </dd>
150  * </dl>
151  * </blockquote>
152  *
153  * @author Chris Warth
154  * @version 1.116, 09/05/07
155  * @see java.net.InetAddress#getByAddress(byte[])
156  * @see java.net.InetAddress#getByAddress(java.lang.String, byte[])
157  * @see java.net.InetAddress#getAllByName(java.lang.String)
158  * @see java.net.InetAddress#getByName(java.lang.String)
159  * @see java.net.InetAddress#getLocalHost()
160  * @since JDK1.0
161  */

162 public
163 class InetAddress implements java.io.Serializable JavaDoc {
164     /**
165      * Specify the address family: Internet Protocol, Version 4
166      * @since 1.4
167      */

168     static final int IPv4 = 1;
169
170     /**
171      * Specify the address family: Internet Protocol, Version 6
172      * @since 1.4
173      */

174     static final int IPv6 = 2;
175
176     /* Specify address family preference */
177     static transient boolean preferIPv6Address = false;
178
179     /**
180      * @serial
181      */

182     String JavaDoc hostName;
183
184     /**
185      * Holds a 32-bit IPv4 address.
186      *
187      * @serial
188      */

189     int address;
190
191     /**
192      * Specifies the address family type, for instance, '1' for IPv4
193      * addresses, and '2' for IPv6 addresses.
194      *
195      * @serial
196      */

197     int family;
198
199     /* Used to store the name service provider */
200     private static NameService nameService = null;
201
202     /* Used to store the best available hostname */
203     private transient String JavaDoc canonicalHostName = null;
204
205     /** use serialVersionUID from JDK 1.0.2 for interoperability */
206     private static final long serialVersionUID = 3286316764910316507L;
207
208     /*
209      * Load net library into runtime, and perform initializations.
210      */

211     static {
212     preferIPv6Address =
213         ((Boolean JavaDoc)java.security.AccessController.doPrivileged(
214          new GetBooleanAction("java.net.preferIPv6Addresses"))).booleanValue();
215     AccessController.doPrivileged(new LoadLibraryAction("net"));
216         init();
217     }
218
219     /**
220      * Constructor for the Socket.accept() method.
221      * This creates an empty InetAddress, which is filled in by
222      * the accept() method. This InetAddress, however, is not
223      * put in the address cache, since it is not created by name.
224      */

225     InetAddress() {
226     }
227
228     /**
229      * Replaces the de-serialized object with an Inet4Address object.
230      *
231      * @return the alternate object to the de-serialized object.
232      *
233      * @throws ObjectStreamException if a new object replacing this
234      * object could not be created
235      */

236     private Object JavaDoc readResolve() throws ObjectStreamException JavaDoc {
237     // will replace the deserialized 'this' object
238
return new Inet4Address JavaDoc(this.hostName, this.address);
239     }
240
241     /**
242      * Utility routine to check if the InetAddress is an
243      * IP multicast address.
244      * @return a <code>boolean</code> indicating if the InetAddress is
245      * an IP multicast address
246      * @since JDK1.1
247      */

248     public boolean isMulticastAddress() {
249     return false;
250     }
251
252     /**
253      * Utility routine to check if the InetAddress in a wildcard address.
254      * @return a <code>boolean</code> indicating if the Inetaddress is
255      * a wildcard address.
256      * @since 1.4
257      */

258     public boolean isAnyLocalAddress() {
259     return false;
260     }
261
262     /**
263      * Utility routine to check if the InetAddress is a loopback address.
264      *
265      * @return a <code>boolean</code> indicating if the InetAddress is
266      * a loopback address; or false otherwise.
267      * @since 1.4
268      */

269     public boolean isLoopbackAddress() {
270     return false;
271     }
272
273     /**
274      * Utility routine to check if the InetAddress is an link local address.
275      *
276      * @return a <code>boolean</code> indicating if the InetAddress is
277      * a link local address; or false if address is not a link local unicast address.
278      * @since 1.4
279      */

280     public boolean isLinkLocalAddress() {
281     return false;
282     }
283
284     /**
285      * Utility routine to check if the InetAddress is a site local address.
286      *
287      * @return a <code>boolean</code> indicating if the InetAddress is
288      * a site local address; or false if address is not a site local unicast address.
289      * @since 1.4
290      */

291     public boolean isSiteLocalAddress() {
292     return false;
293     }
294
295     /**
296      * Utility routine to check if the multicast address has global scope.
297      *
298      * @return a <code>boolean</code> indicating if the address has
299      * is a multicast address of global scope, false if it is not
300      * of global scope or it is not a multicast address
301      * @since 1.4
302      */

303     public boolean isMCGlobal() {
304     return false;
305     }
306
307     /**
308      * Utility routine to check if the multicast address has node scope.
309      *
310      * @return a <code>boolean</code> indicating if the address has
311      * is a multicast address of node-local scope, false if it is not
312      * of node-local scope or it is not a multicast address
313      * @since 1.4
314      */

315     public boolean isMCNodeLocal() {
316     return false;
317     }
318
319     /**
320      * Utility routine to check if the multicast address has link scope.
321      *
322      * @return a <code>boolean</code> indicating if the address has
323      * is a multicast address of link-local scope, false if it is not
324      * of link-local scope or it is not a multicast address
325      * @since 1.4
326      */

327     public boolean isMCLinkLocal() {
328     return false;
329     }
330
331     /**
332      * Utility routine to check if the multicast address has site scope.
333      *
334      * @return a <code>boolean</code> indicating if the address has
335      * is a multicast address of site-local scope, false if it is not
336      * of site-local scope or it is not a multicast address
337      * @since 1.4
338      */

339     public boolean isMCSiteLocal() {
340     return false;
341     }
342
343     /**
344      * Utility routine to check if the multicast address has organization scope.
345      *
346      * @return a <code>boolean</code> indicating if the address has
347      * is a multicast address of organization-local scope,
348      * false if it is not of organization-local scope
349      * or it is not a multicast address
350      * @since 1.4
351      */

352     public boolean isMCOrgLocal() {
353     return false;
354     }
355
356
357     /**
358      * Test whether that address is reachable. Best effort is made by the
359      * implementation to try to reach the host, but firewalls and server
360      * configuration may block requests resulting in a unreachable status
361      * while some specific ports may be accessible.
362      * A typical implementation will use ICMP ECHO REQUESTs if the
363      * privilege can be obtained, otherwise it will try to establish
364      * a TCP connection on port 7 (Echo) of the destination host.
365      * <p>
366      * The timeout value, in milliseconds, indicates the maximum amount of time
367      * the try should take. If the operation times out before getting an
368      * answer, the host is deemed unreachable. A negative value will result
369      * in an IllegalArgumentException being thrown.
370      *
371      * @param timeout the time, in milliseconds, before the call aborts
372      * @return a <code>boolean</code> indicating if the address is reachable.
373      * @throws IOException if a network error occurs
374      * @throws IllegalArgumentException if <code>timeout</code> is negative.
375      * @since 1.5
376      */

377     public boolean isReachable(int timeout) throws IOException JavaDoc {
378     return isReachable(null, 0 , timeout);
379     }
380
381     /**
382      * Test whether that address is reachable. Best effort is made by the
383      * implementation to try to reach the host, but firewalls and server
384      * configuration may block requests resulting in a unreachable status
385      * while some specific ports may be accessible.
386      * A typical implementation will use ICMP ECHO REQUESTs if the
387      * privilege can be obtained, otherwise it will try to establish
388      * a TCP connection on port 7 (Echo) of the destination host.
389      * <p>
390      * The <code>network interface</code> and <code>ttl</code> parameters
391      * let the caller specify which network interface the test will go through
392      * and the maximum number of hops the packets should go through.
393      * A negative value for the <code>ttl</code> will result in an
394      * IllegalArgumentException being thrown.
395      * <p>
396      * The timeout value, in milliseconds, indicates the maximum amount of time
397      * the try should take. If the operation times out before getting an
398      * answer, the host is deemed unreachable. A negative value will result
399      * in an IllegalArgumentException being thrown.
400      *
401      * @param netif the NetworkInterface through which the
402      * test will be done, or null for any interface
403      * @param ttl the maximum numbers of hops to try or 0 for the
404      * default
405      * @param timeout the time, in milliseconds, before the call aborts
406      * @throws IllegalArgumentException if either <code>timeout</code>
407      * or <code>ttl</code> are negative.
408      * @return a <code>boolean</code>indicating if the address is reachable.
409      * @throws IOException if a network error occurs
410      * @since 1.5
411      */

412     public boolean isReachable(NetworkInterface JavaDoc netif, int ttl,
413                    int timeout) throws IOException JavaDoc {
414     if (ttl < 0)
415         throw new IllegalArgumentException JavaDoc("ttl can't be negative");
416     if (timeout < 0)
417         throw new IllegalArgumentException JavaDoc("timeout can't be negative");
418
419     return impl.isReachable(this, timeout, netif, ttl);
420     }
421
422     /**
423      * Gets the host name for this IP address.
424      *
425      * <p>If this InetAddress was created with a host name,
426      * this host name will be remembered and returned;
427      * otherwise, a reverse name lookup will be performed
428      * and the result will be returned based on the system
429      * configured name lookup service. If a lookup of the name service
430      * is required, call
431      * {@link #getCanonicalHostName() getCanonicalHostName}.
432      *
433      * <p>If there is a security manager, its
434      * <code>checkConnect</code> method is first called
435      * with the hostname and <code>-1</code>
436      * as its arguments to see if the operation is allowed.
437      * If the operation is not allowed, it will return
438      * the textual representation of the IP address.
439      *
440      * @return the host name for this IP address, or if the operation
441      * is not allowed by the security check, the textual
442      * representation of the IP address.
443      *
444      * @see InetAddress#getCanonicalHostName
445      * @see SecurityManager#checkConnect
446      */

447     public String JavaDoc getHostName() {
448     return getHostName(true);
449     }
450
451     /**
452      * Returns the hostname for this address.
453      * If the host is equal to null, then this address refers to any
454      * of the local machine's available network addresses.
455      * this is package private so SocketPermission can make calls into
456      * here without a security check.
457      *
458      * <p>If there is a security manager, this method first
459      * calls its <code>checkConnect</code> method
460      * with the hostname and <code>-1</code>
461      * as its arguments to see if the calling code is allowed to know
462      * the hostname for this IP address, i.e., to connect to the host.
463      * If the operation is not allowed, it will return
464      * the textual representation of the IP address.
465      *
466      * @return the host name for this IP address, or if the operation
467      * is not allowed by the security check, the textual
468      * representation of the IP address.
469      *
470      * @param check make security check if true
471      *
472      * @see SecurityManager#checkConnect
473      */

474     String JavaDoc getHostName(boolean check) {
475     if (hostName == null) {
476         hostName = InetAddress.getHostFromNameService(this, check);
477     }
478     return hostName;
479     }
480
481     /**
482      * Gets the fully qualified domain name for this IP address.
483      * Best effort method, meaning we may not be able to return
484      * the FQDN depending on the underlying system configuration.
485      *
486      * <p>If there is a security manager, this method first
487      * calls its <code>checkConnect</code> method
488      * with the hostname and <code>-1</code>
489      * as its arguments to see if the calling code is allowed to know
490      * the hostname for this IP address, i.e., to connect to the host.
491      * If the operation is not allowed, it will return
492      * the textual representation of the IP address.
493      *
494      * @return the fully qualified domain name for this IP address,
495      * or if the operation is not allowed by the security check,
496      * the textual representation of the IP address.
497      *
498      * @see SecurityManager#checkConnect
499      *
500      * @since 1.4
501      */

502     public String JavaDoc getCanonicalHostName() {
503     if (canonicalHostName == null) {
504         canonicalHostName =
505         InetAddress.getHostFromNameService(this, true);
506     }
507     return canonicalHostName;
508     }
509
510     /**
511      * Returns the hostname for this address.
512      *
513      * <p>If there is a security manager, this method first
514      * calls its <code>checkConnect</code> method
515      * with the hostname and <code>-1</code>
516      * as its arguments to see if the calling code is allowed to know
517      * the hostname for this IP address, i.e., to connect to the host.
518      * If the operation is not allowed, it will return
519      * the textual representation of the IP address.
520      *
521      * @return the host name for this IP address, or if the operation
522      * is not allowed by the security check, the textual
523      * representation of the IP address.
524      *
525      * @param check make security check if true
526      *
527      * @see SecurityManager#checkConnect
528      */

529     private static String JavaDoc getHostFromNameService(InetAddress JavaDoc addr, boolean check) {
530     String JavaDoc host;
531     try {
532         // first lookup the hostname
533
host = nameService.getHostByAddr(addr.getAddress());
534
535         /* check to see if calling code is allowed to know
536          * the hostname for this IP address, ie, connect to the host
537          */

538         if (check) {
539         SecurityManager JavaDoc sec = System.getSecurityManager();
540         if (sec != null) {
541             sec.checkConnect(host, -1);
542         }
543         }
544
545         /* now get all the IP addresses for this hostname,
546          * and make sure one of them matches the original IP
547          * address. We do this to try and prevent spoofing.
548          */

549         
550         InetAddress JavaDoc[] arr = InetAddress.getAllByName0(host, check);
551         boolean ok = false;
552
553         if(arr != null) {
554         for(int i = 0; !ok && i < arr.length; i++) {
555             ok = addr.equals(arr[i]);
556         }
557         }
558
559         //XXX: if it looks a spoof just return the address?
560
if (!ok) {
561         host = addr.getHostAddress();
562         return host;
563         }
564
565     } catch (SecurityException JavaDoc e) {
566         host = addr.getHostAddress();
567     } catch (UnknownHostException JavaDoc e) {
568         host = addr.getHostAddress();
569     }
570     return host;
571     }
572
573     /**
574      * Returns the raw IP address of this <code>InetAddress</code>
575      * object. The result is in network byte order: the highest order
576      * byte of the address is in <code>getAddress()[0]</code>.
577      *
578      * @return the raw IP address of this object.
579      */

580     public byte[] getAddress() {
581     return null;
582     }
583
584     /**
585      * Returns the IP address string in textual presentation.
586      *
587      * @return the raw IP address in a string format.
588      * @since JDK1.0.2
589      */

590     public String JavaDoc getHostAddress() {
591     return null;
592      }
593     
594     /**
595      * Returns a hashcode for this IP address.
596      *
597      * @return a hash code value for this IP address.
598      */

599     public int hashCode() {
600     return -1;
601     }
602    
603     /**
604      * Compares this object against the specified object.
605      * The result is <code>true</code> if and only if the argument is
606      * not <code>null</code> and it represents the same IP address as
607      * this object.
608      * <p>
609      * Two instances of <code>InetAddress</code> represent the same IP
610      * address if the length of the byte arrays returned by
611      * <code>getAddress</code> is the same for both, and each of the
612      * array components is the same for the byte arrays.
613      *
614      * @param obj the object to compare against.
615      * @return <code>true</code> if the objects are the same;
616      * <code>false</code> otherwise.
617      * @see java.net.InetAddress#getAddress()
618      */

619     public boolean equals(Object JavaDoc obj) {
620     return false;
621     }
622
623     /**
624      * Converts this IP address to a <code>String</code>. The
625      * string returned is of the form: hostname / literal IP
626      * address.
627      *
628      * If the host name is unresolved, no reverse name service loopup
629      * is performed. The hostname part will be represented by an empty string.
630      *
631      * @return a string representation of this IP address.
632      */

633     public String JavaDoc toString() {
634     return ((hostName != null) ? hostName : "")
635         + "/" + getHostAddress();
636     }
637
638     /*
639      * Cached addresses - our own litle nis, not!
640      */

641     private static Cache addressCache = new Cache(Cache.Type.Positive);
642
643     private static Cache negativeCache = new Cache(Cache.Type.Negative);
644
645     private static boolean addressCacheInit = false;
646
647     static InetAddress JavaDoc[] unknown_array; // put THIS in cache
648

649     static InetAddressImpl JavaDoc impl;
650
651     private static HashMap JavaDoc lookupTable = new HashMap JavaDoc();
652
653     /**
654      * Represents a cache entry
655      */

656     static final class CacheEntry {
657
658         CacheEntry(Object JavaDoc address, long expiration) {
659             this.address = address;
660             this.expiration = expiration;
661         }
662
663         Object JavaDoc address;
664         long expiration;
665     }
666
667     /**
668      * A cache that manages entries based on a policy specified
669      * at creation time.
670      */

671     static final class Cache {
672     private LinkedHashMap JavaDoc cache;
673     private Type type;
674
675     enum Type {Positive, Negative};
676
677     /**
678      * Create cache
679      */

680     public Cache(Type type) {
681         this.type = type;
682         cache = new LinkedHashMap JavaDoc();
683     }
684
685     private int getPolicy() {
686         if (type == Type.Positive) {
687         return InetAddressCachePolicy.get();
688         } else {
689         return InetAddressCachePolicy.getNegative();
690         }
691     }
692
693     /**
694      * Add an entry to the cache. If there's already an
695      * entry then for this host then the entry will be
696      * replaced.
697      */

698     public Cache put(String JavaDoc host, Object JavaDoc address) {
699         int policy = getPolicy();
700         if (policy == InetAddressCachePolicy.NEVER) {
701                 return this;
702         }
703
704         // purge any expired entries
705

706         if (policy != InetAddressCachePolicy.FOREVER) {
707
708         // As we iterate in insertion order we can
709
// terminate when a non-expired entry is found.
710
LinkedList JavaDoc expired = new LinkedList JavaDoc();
711                 Iterator JavaDoc i = cache.keySet().iterator();
712         long now = System.currentTimeMillis();
713                 while (i.hasNext()) {
714                     String JavaDoc key = (String JavaDoc)i.next();
715                     CacheEntry entry = (CacheEntry)cache.get(key);
716
717                     if (entry.expiration >= 0 && entry.expiration < now) {
718                         expired.add(key);
719                     } else {
720                         break;
721                     }
722                 }
723
724                 i = expired.iterator();
725                 while (i.hasNext()) {
726                     cache.remove(i.next());
727         }
728             }
729
730         // create new entry and add it to the cache
731
// -- as a HashMap replaces existing entries we
732
// don't need to explicitly check if there is
733
// already an entry for this host.
734
long expiration;
735         if (policy == InetAddressCachePolicy.FOREVER) {
736         expiration = -1;
737         } else {
738         expiration = System.currentTimeMillis() + (policy * 1000);
739         }
740         CacheEntry entry = new CacheEntry(address, expiration);
741         cache.put(host, entry);
742         return this;
743     }
744
745     /**
746      * Query the cache for the specific host. If found then
747      * return its CacheEntry, or null if not found.
748      */

749     public CacheEntry get(String JavaDoc host) {
750         int policy = getPolicy();
751         if (policy == InetAddressCachePolicy.NEVER) {
752         return null;
753         }
754         CacheEntry entry = (CacheEntry)cache.get(host);
755
756         // check if entry has expired
757
if (entry != null && policy != InetAddressCachePolicy.FOREVER) {
758         if (entry.expiration >= 0 &&
759             entry.expiration < System.currentTimeMillis()) {
760             cache.remove(host);
761             entry = null;
762         }
763         }
764
765         return entry;
766     }
767     }
768
769     /*
770      * Initialize cache and insert anyLocalAddress into the
771      * unknown array with no expiry.
772      */

773     private static void cacheInitIfNeeded() {
774         assert Thread.holdsLock(addressCache);
775         if (addressCacheInit) {
776             return;
777         }
778         unknown_array = new InetAddress JavaDoc[1];
779         unknown_array[0] = impl.anyLocalAddress();
780
781     addressCache.put(impl.anyLocalAddress().getHostName(),
782                      unknown_array);
783
784         addressCacheInit = true;
785     }
786
787     /*
788      * Cache the given hostname and address.
789      */

790     private static void cacheAddress(String JavaDoc hostname, Object JavaDoc address,
791                      boolean success) {
792     hostname = hostname.toLowerCase();
793     synchronized (addressCache) {
794         cacheInitIfNeeded();
795         if (success) {
796         addressCache.put(hostname, address);
797         } else {
798         negativeCache.put(hostname, address);
799         }
800     }
801     }
802
803     /*
804      * Lookup hostname in cache (positive & negative cache). If
805      * found return address, null if not found.
806      */

807     private static Object JavaDoc getCachedAddress(String JavaDoc hostname) {
808         hostname = hostname.toLowerCase();
809
810     // search both positive & negative caches
811

812     synchronized (addressCache) {
813         CacheEntry entry;
814
815         cacheInitIfNeeded();
816
817         entry = (CacheEntry)addressCache.get(hostname);
818         if (entry == null) {
819         entry = (CacheEntry)negativeCache.get(hostname);
820         }
821
822         if (entry != null) {
823             return entry.address;
824         }
825     }
826
827     // not found
828
return null;
829     }
830
831     static {
832     // create the impl
833
impl = (new InetAddressImplFactory()).create();
834
835     // get name service if provided and requested
836
String JavaDoc provider = null;;
837     String JavaDoc propPrefix = "sun.net.spi.nameservice.provider.";
838     int n = 1;
839         while (nameService == null) {
840         provider
841             = (String JavaDoc)AccessController.doPrivileged(
842             new GetPropertyAction(propPrefix+n, "default"));
843         n++;
844         if (provider.equals("default")) {
845             // initialize the default name service
846
nameService = new NameService() {
847             public InetAddress JavaDoc[] lookupAllHostAddr(String JavaDoc host)
848                 throws UnknownHostException JavaDoc {
849                 return impl.lookupAllHostAddr(host);
850             }
851             public String JavaDoc getHostByAddr(byte[] addr)
852                 throws UnknownHostException JavaDoc {
853                 return impl.getHostByAddr(addr);
854             }
855             };
856             break;
857         }
858
859         final String JavaDoc providerName = provider;
860
861         try {
862             java.security.AccessController.doPrivileged(
863             new java.security.PrivilegedExceptionAction JavaDoc() {
864                 public Object JavaDoc run() {
865                 Iterator JavaDoc itr
866                         = Service.providers(NameServiceDescriptor.class);
867                 while (itr.hasNext()) {
868                         NameServiceDescriptor nsd
869                     = (NameServiceDescriptor)itr.next();
870                         if (providerName.
871                         equalsIgnoreCase(nsd.getType()+","
872                             +nsd.getProviderName())) {
873                     try {
874                                 nameService = nsd.createNameService();
875                                 break;
876                     } catch (Exception JavaDoc e) {
877                         e.printStackTrace();
878                                 System.err.println(
879                         "Cannot create name service:"
880                              +providerName+": " + e);
881                     }
882                         }
883                 } /* while */
884                     return null;
885             }
886             });
887         } catch (java.security.PrivilegedActionException JavaDoc e) {
888         }
889
890         }
891     }
892     
893     /**
894      * Create an InetAddress based on the provided host name and IP address
895      * No name service is checked for the validity of the address.
896      *
897      * <p> The host name can either be a machine name, such as
898      * "<code>java.sun.com</code>", or a textual representation of its IP
899      * address.
900      * <p> No validity checking is done on the host name either.
901      *
902      * <p> If addr specifies an IPv4 address an instance of Inet4Address
903      * will be returned; otherwise, an instance of Inet6Address
904      * will be returned.
905      *
906      * <p> IPv4 address byte array must be 4 bytes long and IPv6 byte array
907      * must be 16 bytes long
908      *
909      * @param host the specified host
910      * @param addr the raw IP address in network byte order
911      * @return an InetAddress object created from the raw IP address.
912      * @exception UnknownHostException if IP address is of illegal length
913      * @since 1.4
914      */

915     public static InetAddress JavaDoc getByAddress(String JavaDoc host, byte[] addr)
916     throws UnknownHostException JavaDoc {
917     if (host != null && host.length() > 0 && host.charAt(0) == '[') {
918         if (host.charAt(host.length()-1) == ']') {
919         host = host.substring(1, host.length() -1);
920         }
921     }
922     if (addr != null) {
923         if (addr.length == Inet4Address.INADDRSZ) {
924         return new Inet4Address JavaDoc(host, addr);
925         } else if (addr.length == Inet6Address.INADDRSZ) {
926         byte[] newAddr
927             = IPAddressUtil.convertFromIPv4MappedAddress(addr);
928         if (newAddr != null) {
929             return new Inet4Address JavaDoc(host, newAddr);
930         } else {
931             return new Inet6Address JavaDoc(host, addr);
932         }
933         }
934     }
935     throw new UnknownHostException JavaDoc("addr is of illegal length");
936     }
937
938
939     /**
940      * Determines the IP address of a host, given the host's name.
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
944      * IP address. If a literal IP address is supplied, only the
945      * validity of the address format is checked.
946      *
947      * <p> For <code>host</code> specified in literal IPv6 address,
948      * either the form defined in RFC 2732 or the literal IPv6 address
949      * format defined in RFC 2373 is accepted. IPv6 scoped addresses are also
950      * supported. See <a HREF="Inet6Address.html#scoped">here</a> for a description of IPv6
951      * scoped addresses.
952      *
953      * <p> If the host is <tt>null</tt> then an <tt>InetAddress</tt>
954      * representing an address of the loopback interface is returned.
955      * See <a HREF="http://www.ietf.org/rfc/rfc3330.txt">RFC&nbsp;3330</a>
956      * section&nbsp;2 and <a HREF="http://www.ietf.org/rfc/rfc2373.txt">RFC&nbsp;2373</a>
957      * section&nbsp;2.5.3. </p>
958      *
959      * @param host the specified host, or <code>null</code>.
960      * @return an IP address for the given host name.
961      * @exception UnknownHostException if no IP address for the
962      * <code>host</code> could be found, or if a scope_id was specified
963      * for a global IPv6 address.
964      * @exception SecurityException if a security manager exists
965      * and its checkConnect method doesn't allow the operation
966      */

967     public static InetAddress JavaDoc getByName(String JavaDoc host)
968     throws UnknownHostException JavaDoc {
969     return InetAddress.getAllByName(host)[0];
970     }
971
972     // called from deployment cache manager
973
private static InetAddress JavaDoc getByName(String JavaDoc host, InetAddress JavaDoc reqAddr)
974     throws UnknownHostException JavaDoc {
975     return InetAddress.getAllByName(host, reqAddr)[0];
976     }
977
978     /**
979      * Given the name of a host, returns an array of its IP addresses,
980 &nbs