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      * based on the configured name service on the system.
981      *
982      * <p> The host name can either be a machine name, such as
983      * "<code>java.sun.com</code>", or a textual representation of its IP
984      * address. If a literal IP address is supplied, only the
985      * validity of the address format is checked.
986      *
987      * <p> For <code>host</code> specified in <i>literal IPv6 address</i>,
988      * either the form defined in RFC 2732 or the literal IPv6 address
989      * format defined in RFC 2373 is accepted. A literal IPv6 address may
990      * also be qualified by appending a scoped zone identifier or scope_id.
991      * The syntax and usage of scope_ids is described
992      * <a HREF="Inet6Address.html#scoped">here</a>.
993      * <p> If the host is <tt>null</tt> then an <tt>InetAddress</tt>
994      * representing an address of the loopback interface is returned.
995      * See <a HREF="http://www.ietf.org/rfc/rfc3330.txt">RFC&nbsp;3330</a>
996      * section&nbsp;2 and <a HREF="http://www.ietf.org/rfc/rfc2373.txt">RFC&nbsp;2373</a>
997      * section&nbsp;2.5.3. </p>
998      *
999      * <p> If there is a security manager and <code>host</code> is not
1000     * null and <code>host.length() </code> is not equal to zero, the
1001     * security manager's
1002     * <code>checkConnect</code> method is called
1003     * with the hostname and <code>-1</code>
1004     * as its arguments to see if the operation is allowed.
1005     *
1006     * @param host the name of the host, or <code>null</code>.
1007     * @return an array of all the IP addresses for a given host name.
1008     *
1009     * @exception UnknownHostException if no IP address for the
1010     * <code>host</code> could be found, or if a scope_id was specified
1011     * for a global IPv6 address.
1012     * @exception SecurityException if a security manager exists and its
1013     * <code>checkConnect</code> method doesn't allow the operation.
1014     *
1015     * @see SecurityManager#checkConnect
1016     */

1017    public static InetAddress JavaDoc[] getAllByName(String JavaDoc host)
1018    throws UnknownHostException JavaDoc {
1019    return getAllByName(host, null);
1020    }
1021
1022    private static InetAddress JavaDoc[] getAllByName(String JavaDoc host, InetAddress JavaDoc reqAddr)
1023    throws UnknownHostException JavaDoc {
1024
1025    if (host == null || host.length() == 0) {
1026        InetAddress JavaDoc[] ret = new InetAddress JavaDoc[1];
1027        ret[0] = impl.loopbackAddress();
1028        return ret;
1029    }
1030    
1031    boolean ipv6Expected = false;
1032    if (host.charAt(0) == '[') {
1033        // This is supposed to be an IPv6 litteral
1034
if (host.length() > 2 && host.charAt(host.length()-1) == ']') {
1035        host = host.substring(1, host.length() -1);
1036        ipv6Expected = true;
1037        } else {
1038        // This was supposed to be a IPv6 address, but it's not!
1039
throw new UnknownHostException JavaDoc(host);
1040        }
1041    }
1042
1043    // if host is an IP address, we won't do further lookup
1044
if (Character.digit(host.charAt(0), 16) != -1
1045        || (host.charAt(0) == ':')) {
1046        byte[] addr = null;
1047        int numericZone = -1;
1048        String JavaDoc ifname = null;
1049        // see if it is IPv4 address
1050
addr = IPAddressUtil.textToNumericFormatV4(host);
1051        if (addr == null) {
1052        // see if it is IPv6 address
1053
// Check if a numeric or string zone id is present
1054
int pos;
1055        if ((pos=host.indexOf ("%")) != -1) {
1056            numericZone = checkNumericZone (host);
1057            if (numericZone == -1) { /* remainder of string must be an ifname */
1058            ifname = host.substring (pos+1);
1059            }
1060        }
1061        addr = IPAddressUtil.textToNumericFormatV6(host);
1062        } else if (ipv6Expected) {
1063        // Means an IPv4 litteral between brackets!
1064
throw new UnknownHostException JavaDoc("["+host+"]");
1065        }
1066        InetAddress JavaDoc[] ret = new InetAddress JavaDoc[1];
1067        if(addr != null) {
1068        if (addr.length == Inet4Address.INADDRSZ) {
1069            ret[0] = new Inet4Address JavaDoc(null, addr);
1070        } else {
1071            if (ifname != null) {
1072                ret[0] = new Inet6Address JavaDoc(null, addr, ifname);
1073            } else {
1074                ret[0] = new Inet6Address JavaDoc(null, addr, numericZone);
1075            }
1076        }
1077        return ret;
1078        }
1079        } else if (ipv6Expected) {
1080        // We were expecting an IPv6 Litteral, but got something else
1081
throw new UnknownHostException JavaDoc("["+host+"]");
1082        }
1083    return getAllByName0(host, reqAddr, true);
1084    }
1085
1086    /**
1087     * check if the literal address string has %nn appended
1088     * returns -1 if not, or the numeric value otherwise.
1089     *
1090     * %nn may also be a string that represents the displayName of
1091     * a currently available NetworkInterface.
1092     */

1093    private static int checkNumericZone (String JavaDoc s) throws UnknownHostException JavaDoc {
1094    int percent = s.indexOf ('%');
1095    int slen = s.length();
1096    int digit, zone=0;
1097    if (percent == -1) {
1098        return -1;
1099    }
1100    for (int i=percent+1; i<slen; i++) {
1101        char c = s.charAt(i);
1102        if (c == ']') {
1103        if (i == percent+1) {
1104            /* empty per-cent field */
1105            return -1;
1106        }
1107        break;
1108        }
1109        if ((digit = Character.digit (c, 10)) < 0) {
1110        return -1;
1111        }
1112        zone = (zone * 10) + digit;
1113    }
1114    return zone;
1115    }
1116
1117    private static InetAddress JavaDoc[] getAllByName0 (String JavaDoc host)
1118    throws UnknownHostException JavaDoc
1119    {
1120    return getAllByName0(host, true);
1121    }
1122
1123    /**
1124     * package private so SocketPermission can call it
1125     */

1126    static InetAddress JavaDoc[] getAllByName0 (String JavaDoc host, boolean check)
1127    throws UnknownHostException JavaDoc {
1128    return getAllByName0 (host, null, check);
1129    }
1130
1131    private static InetAddress JavaDoc[] getAllByName0 (String JavaDoc host, InetAddress JavaDoc reqAddr, boolean check)
1132    throws UnknownHostException JavaDoc {
1133
1134    /* If it gets here it is presumed to be a hostname */
1135    /* Cache.get can return: null, unknownAddress, or InetAddress[] */
1136        Object JavaDoc obj = null;
1137    Object JavaDoc objcopy = null;
1138
1139    /* make sure the connection to the host is allowed, before we
1140     * give out a hostname
1141     */

1142    if (check) {
1143        SecurityManager JavaDoc security = System.getSecurityManager();
1144        if (security != null) {
1145        security.checkConnect(host, -1);
1146        }
1147    }
1148
1149    obj = getCachedAddress(host);
1150
1151    /* If no entry in cache, then do the host lookup */
1152    if (obj == null) {
1153        obj = getAddressFromNameService(host, reqAddr);
1154    }
1155
1156    if (obj == unknown_array)
1157        throw new UnknownHostException JavaDoc(host);
1158
1159    /* Make a copy of the InetAddress array */
1160    objcopy = ((InetAddress JavaDoc [])obj).clone();
1161
1162    return (InetAddress JavaDoc [])objcopy;
1163    }
1164
1165    private static Object JavaDoc getAddressFromNameService(String JavaDoc host, InetAddress JavaDoc reqAddr)
1166    throws UnknownHostException JavaDoc
1167    {
1168    Object JavaDoc obj = null;
1169    boolean success = false;
1170
1171    // Check whether the host is in the lookupTable.
1172
// 1) If the host isn't in the lookupTable when
1173
// checkLookupTable() is called, checkLookupTable()
1174
// would add the host in the lookupTable and
1175
// return null. So we will do the lookup.
1176
// 2) If the host is in the lookupTable when
1177
// checkLookupTable() is called, the current thread
1178
// would be blocked until the host is removed
1179
// from the lookupTable. Then this thread
1180
// should try to look up the addressCache.
1181
// i) if it found the address in the
1182
// addressCache, checkLookupTable() would
1183
// return the address.
1184
// ii) if it didn't find the address in the
1185
// addressCache for any reason,
1186
// it should add the host in the
1187
// lookupTable and return null so the
1188
// following code would do a lookup itself.
1189
if ((obj = checkLookupTable(host)) == null) {
1190        // This is the first thread which looks up the address
1191
// this host or the cache entry for this host has been
1192
// expired so this thread should do the lookup.
1193
try {
1194        /*
1195         * Do not put the call to lookup() inside the
1196         * constructor. if you do you will still be
1197         * allocating space when the lookup fails.
1198         */

1199         
1200        obj = nameService.lookupAllHostAddr(host);
1201        success = true;
1202        } catch (UnknownHostException JavaDoc uhe) {
1203        if (host.equalsIgnoreCase("localhost")) {
1204            InetAddress JavaDoc[] local = new InetAddress JavaDoc[] { impl.loopbackAddress() };
1205            obj = local;
1206            success = true;
1207        }
1208        else {
1209            obj = unknown_array;
1210            success = false;
1211            throw uhe;
1212        }
1213        } finally {
1214        // More to do?
1215
InetAddress JavaDoc[] addrs = (InetAddress JavaDoc[])obj;
1216        if (reqAddr != null && addrs.length > 1 && !addrs[0].equals(reqAddr)) {
1217            // Find it?
1218
int i = 1;
1219            for (; i < addrs.length; i++) {
1220            if (addrs[i].equals(reqAddr)) {
1221                break;
1222            }
1223            }
1224            // Rotate
1225
if (i < addrs.length) {
1226            InetAddress JavaDoc tmp, tmp2 = reqAddr;
1227            for (int j = 0; j < i; j++) {
1228                tmp = addrs[j];
1229                addrs[j] = tmp2;
1230                tmp2 = tmp;
1231            }
1232            addrs[i] = tmp2;
1233            }
1234        }
1235        // Cache the address.
1236
cacheAddress(host, obj, success);
1237        // Delete the host from the lookupTable, and
1238
// notify all threads waiting for the monitor
1239
// for lookupTable.
1240
updateLookupTable(host);
1241        }
1242    }
1243
1244    return obj;
1245    }
1246    
1247        
1248    private static Object JavaDoc checkLookupTable(String JavaDoc host) {
1249    // make sure obj is null.
1250
Object JavaDoc obj = null;
1251    
1252    synchronized (lookupTable) {
1253        // If the host isn't in the lookupTable, add it in the
1254
// lookuptable and return null. The caller should do
1255
// the lookup.
1256
if (lookupTable.containsKey(host) == false) {
1257        lookupTable.put(host, null);
1258        return obj;
1259        }
1260
1261        // If the host is in the lookupTable, it means that another
1262
// thread is trying to look up the address of this host.
1263
// This thread should wait.
1264
while (lookupTable.containsKey(host)) {
1265        try {
1266            lookupTable.wait();
1267        } catch (InterruptedException JavaDoc e) {
1268        }
1269        }
1270    }
1271
1272    // The other thread has finished looking up the address of
1273
// the host. This thread should retry to get the address
1274
// from the addressCache. If it doesn't get the address from
1275
// the cache, it will try to look up the address itself.
1276
obj = getCachedAddress(host);
1277    if (obj == null) {
1278        synchronized (lookupTable) {
1279        lookupTable.put(host, null);
1280        }
1281    }
1282     
1283    return obj;
1284    }
1285
1286    private static void updateLookupTable(String JavaDoc host) {
1287    synchronized (lookupTable) {
1288        lookupTable.remove(host);
1289        lookupTable.notifyAll();
1290    }
1291    }
1292
1293    /**
1294     * Returns an <code>InetAddress</code> object given the raw IP address .
1295     * The argument is in network byte order: the highest order
1296     * byte of the address is in <code>getAddress()[0]</code>.
1297     *
1298     * <p> This method doesn't block, i.e. no reverse name service lookup
1299     * is performed.
1300     *
1301     * <p> IPv4 address byte array must be 4 bytes long and IPv6 byte array
1302     * must be 16 bytes long
1303     *
1304     * @param addr the raw IP address in network byte order
1305     * @return an InetAddress object created from the raw IP address.
1306     * @exception UnknownHostException if IP address is of illegal length
1307     * @since 1.4
1308     */

1309    public static InetAddress JavaDoc getByAddress(byte[] addr)
1310    throws UnknownHostException JavaDoc {
1311    return getByAddress(null, addr);
1312    }
1313
1314    /**
1315     * Returns the local host.
1316     *
1317     * <p>If there is a security manager, its
1318     * <code>checkConnect</code> method is called
1319     * with the local host name and <code>-1</code>
1320     * as its arguments to see if the operation is allowed.
1321     * If the operation is not allowed, an InetAddress representing
1322     * the loopback address is returned.
1323     *
1324     * @return the IP address of the local host.
1325     *
1326     * @exception UnknownHostException if no IP address for the
1327     * <code>host</code> could be found.
1328     *
1329     * @see SecurityManager#checkConnect
1330     */

1331    public static InetAddress JavaDoc getLocalHost() throws UnknownHostException JavaDoc {
1332
1333    SecurityManager JavaDoc security = System.getSecurityManager();
1334    try {
1335        String JavaDoc local = impl.getLocalHostName();
1336
1337        if (security != null) {
1338        security.checkConnect(local, -1);
1339        }
1340
1341        if (local.equals("localhost")) {
1342        return impl.loopbackAddress();
1343        }
1344
1345        // we are calling getAddressFromNameService directly
1346
// to avoid getting localHost from cache
1347

1348        InetAddress JavaDoc[] localAddrs;
1349        try {
1350        localAddrs =
1351            (InetAddress JavaDoc[]) InetAddress.getAddressFromNameService(local, null);
1352        } catch (UnknownHostException JavaDoc uhe) {
1353        throw new UnknownHostException JavaDoc(local + ": " + uhe.getMessage());
1354        }
1355        return localAddrs[0];
1356    } catch (java.lang.SecurityException JavaDoc e) {
1357        return impl.loopbackAddress();
1358    }
1359    }
1360
1361
1362    /**
1363     * Perform class load-time initializations.
1364     */

1365    private static native void init();
1366
1367
1368    /*
1369     * Returns the InetAddress representing anyLocalAddress
1370     * (typically 0.0.0.0 or ::0)
1371     */

1372    static InetAddress JavaDoc anyLocalAddress() {
1373        return impl.anyLocalAddress();
1374    }
1375
1376    /*
1377     * Load and instantiate an underlying impl class
1378     */

1379    static Object JavaDoc loadImpl(String JavaDoc implName) {
1380    Object JavaDoc impl;
1381
1382        /*
1383         * Property "impl.prefix" will be prepended to the classname
1384         * of the implementation object we instantiate, to which we
1385         * delegate the real work (like native methods). This
1386         * property can vary across implementations of the java.
1387         * classes. The default is an empty String "".
1388         */

1389        String JavaDoc prefix = (String JavaDoc)AccessController.doPrivileged(
1390                      new GetPropertyAction("impl.prefix", ""));
1391        impl = null;
1392        try {
1393            impl = Class.forName("java.net." + prefix + implName).newInstance();
1394        } catch (ClassNotFoundException JavaDoc e) {
1395            System.err.println("Class not found: java.net." + prefix +
1396                               implName + ":\ncheck impl.prefix property " +
1397                               "in your properties file.");
1398        } catch (InstantiationException JavaDoc e) {
1399            System.err.println("Could not instantiate: java.net." + prefix +
1400                               implName + ":\ncheck impl.prefix property " +
1401                               "in your properties file.");
1402        } catch (IllegalAccessException JavaDoc e) {
1403            System.err.println("Cannot access class: java.net." + prefix +
1404                               implName + ":\ncheck impl.prefix property " +
1405                               "in your properties file.");
1406        }
1407
1408        if (impl == null) {
1409            try {
1410                impl = Class.forName(implName).newInstance();
1411            } catch (Exception JavaDoc e) {
1412                throw new Error JavaDoc("System property impl.prefix incorrect");
1413            }
1414        }
1415
1416    return impl;
1417    }
1418}
1419
1420/*
1421 * Simple factory to create the impl
1422 */

1423class InetAddressImplFactory {
1424
1425    static InetAddressImpl JavaDoc create() {
1426    Object JavaDoc o;
1427    if (isIPv6Supported()) {
1428        o = InetAddress.loadImpl("Inet6AddressImpl");
1429    } else {
1430        o = InetAddress.loadImpl("Inet4AddressImpl");
1431    }
1432    return (InetAddressImpl JavaDoc)o;
1433    }
1434
1435    static native boolean isIPv6Supported();
1436}
1437
Popular Tags