1 /*
2  * Copyright (c) 1995, 2015, Oracle and/or its affiliates. All rights reserved.
3  * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
4  *
5  *
6  *
7  *
8  *
9  *
10  *
11  *
12  *
13  *
14  *
15  *
16  *
17  *
18  *
19  *
20  *
21  *
22  *
23  *
24  */

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

188 public
189 class InetAddress implements java.io.Serializable {
190     /**
191      * Specify the address family: Internet Protocol, Version 4
192      * @since 1.4
193      */

194     static final int IPv4 = 1;
195
196     /**
197      * Specify the address family: Internet Protocol, Version 6
198      * @since 1.4
199      */

200     static final int IPv6 = 2;
201
202     /* Specify address family preference */
203     static transient boolean preferIPv6Address = false;
204
205     static class InetAddressHolder {
206         /**
207          * Reserve the original application specified hostname.
208          *
209          * The original hostname is useful for domain-based endpoint
210          * identification (see RFC 2818 and RFC 6125).  If an address
211          * was created with a raw IP address, a reverse name lookup
212          * may introduce endpoint identification security issue via
213          * DNS forging.
214          *
215          * Oracle JSSE provider is using this original hostname, via
216          * sun.misc.JavaNetAccess, for SSL/TLS endpoint identification.
217          *
218          * Note: May define a new public method in the future if necessary.
219          */

220         String originalHostName;
221
222         InetAddressHolder() {}
223
224         InetAddressHolder(String hostName, int address, int family) {
225             this.originalHostName = hostName;
226             this.hostName = hostName;
227             this.address = address;
228             this.family = family;
229         }
230
231         void init(String hostName, int family) {
232             this.originalHostName = hostName;
233             this.hostName = hostName;
234             if (family != -1) {
235                 this.family = family;
236             }
237         }
238
239         String hostName;
240
241         String getHostName() {
242             return hostName;
243         }
244
245         String getOriginalHostName() {
246             return originalHostName;
247         }
248
249         /**
250          * Holds a 32-bit IPv4 address.
251          */

252         int address;
253
254         int getAddress() {
255             return address;
256         }
257
258         /**
259          * Specifies the address family type, for instance, '1' for IPv4
260          * addresses, and '2' for IPv6 addresses.
261          */

262         int family;
263
264         int getFamily() {
265             return family;
266         }
267     }
268
269     /* Used to store the serializable fields of InetAddress */
270     final transient InetAddressHolder holder;
271
272     InetAddressHolder holder() {
273         return holder;
274     }
275
276     /* Used to store the name service provider */
277     private static List<NameService> nameServices = null;
278
279     /* Used to store the best available hostname */
280     private transient String canonicalHostName = null;
281
282     /** use serialVersionUID from JDK 1.0.2 for interoperability */
283     private static final long serialVersionUID = 3286316764910316507L;
284
285     /*
286      * Load net library into runtime, and perform initializations.
287      */

288     static {
289         preferIPv6Address = java.security.AccessController.doPrivileged(
290             new GetBooleanAction("java.net.preferIPv6Addresses")).booleanValue();
291         AccessController.doPrivileged(
292             new java.security.PrivilegedAction<Void>() {
293                 public Void run() {
294                     System.loadLibrary("net");
295                     return null;
296                 }
297             });
298         init();
299     }
300
301     /**
302      * Constructor for the Socket.accept() method.
303      * This creates an empty InetAddress, which is filled in by
304      * the accept() method.  This InetAddress, however, is not
305      * put in the address cache, since it is not created by name.
306      */

307     InetAddress() {
308         holder = new InetAddressHolder();
309     }
310
311     /**
312      * Replaces the de-serialized object with an Inet4Address object.
313      *
314      * @return the alternate object to the de-serialized object.
315      *
316      * @throws ObjectStreamException if a new object replacing this
317      * object could not be created
318      */

319     private Object readResolve() throws ObjectStreamException {
320         // will replace the deserialized 'this' object
321         return new Inet4Address(holder().getHostName(), holder().getAddress());
322     }
323
324     /**
325      * Utility routine to check if the InetAddress is an
326      * IP multicast address.
327      * @return a {@code boolean} indicating if the InetAddress is
328      * an IP multicast address
329      * @since   JDK1.1
330      */

331     public boolean isMulticastAddress() {
332         return false;
333     }
334
335     /**
336      * Utility routine to check if the InetAddress in a wildcard address.
337      * @return a {@code boolean} indicating if the Inetaddress is
338      *         a wildcard address.
339      * @since 1.4
340      */

341     public boolean isAnyLocalAddress() {
342         return false;
343     }
344
345     /**
346      * Utility routine to check if the InetAddress is a loopback address.
347      *
348      * @return a {@code boolean} indicating if the InetAddress is
349      * a loopback address; or false otherwise.
350      * @since 1.4
351      */

352     public boolean isLoopbackAddress() {
353         return false;
354     }
355
356     /**
357      * Utility routine to check if the InetAddress is an link local address.
358      *
359      * @return a {@code boolean} indicating if the InetAddress is
360      * a link local address; or false if address is not a link local unicast address.
361      * @since 1.4
362      */

363     public boolean isLinkLocalAddress() {
364         return false;
365     }
366
367     /**
368      * Utility routine to check if the InetAddress is a site local address.
369      *
370      * @return a {@code boolean} indicating if the InetAddress is
371      * a site local address; or false if address is not a site local unicast address.
372      * @since 1.4
373      */

374     public boolean isSiteLocalAddress() {
375         return false;
376     }
377
378     /**
379      * Utility routine to check if the multicast address has global scope.
380      *
381      * @return a {@code boolean} indicating if the address has
382      *         is a multicast address of global scope, false if it is not
383      *         of global scope or it is not a multicast address
384      * @since 1.4
385      */

386     public boolean isMCGlobal() {
387         return false;
388     }
389
390     /**
391      * Utility routine to check if the multicast address has node scope.
392      *
393      * @return a {@code boolean} indicating if the address has
394      *         is a multicast address of node-local scope, false if it is not
395      *         of node-local scope or it is not a multicast address
396      * @since 1.4
397      */

398     public boolean isMCNodeLocal() {
399         return false;
400     }
401
402     /**
403      * Utility routine to check if the multicast address has link scope.
404      *
405      * @return a {@code boolean} indicating if the address has
406      *         is a multicast address of link-local scope, false if it is not
407      *         of link-local scope or it is not a multicast address
408      * @since 1.4
409      */

410     public boolean isMCLinkLocal() {
411         return false;
412     }
413
414     /**
415      * Utility routine to check if the multicast address has site scope.
416      *
417      * @return a {@code boolean} indicating if the address has
418      *         is a multicast address of site-local scope, false if it is not
419      *         of site-local scope or it is not a multicast address
420      * @since 1.4
421      */

422     public boolean isMCSiteLocal() {
423         return false;
424     }
425
426     /**
427      * Utility routine to check if the multicast address has organization scope.
428      *
429      * @return a {@code boolean} indicating if the address has
430      *         is a multicast address of organization-local scope,
431      *         false if it is not of organization-local scope
432      *         or it is not a multicast address
433      * @since 1.4
434      */

435     public boolean isMCOrgLocal() {
436         return false;
437     }
438
439
440     /**
441      * Test whether that address is reachable. Best effort is made by the
442      * implementation to try to reach the host, but firewalls and server
443      * configuration may block requests resulting in a unreachable status
444      * while some specific ports may be accessible.
445      * A typical implementation will use ICMP ECHO REQUESTs if the
446      * privilege can be obtained, otherwise it will try to establish
447      * a TCP connection on port 7 (Echo) of the destination host.
448      * <p>
449      * The timeout value, in milliseconds, indicates the maximum amount of time
450      * the try should take. If the operation times out before getting an
451      * answer, the host is deemed unreachable. A negative value will result
452      * in an IllegalArgumentException being thrown.
453      *
454      * @param   timeout the time, in milliseconds, before the call aborts
455      * @return a {@code boolean} indicating if the address is reachable.
456      * @throws IOException if a network error occurs
457      * @throws  IllegalArgumentException if {@code timeout} is negative.
458      * @since 1.5
459      */

460     public boolean isReachable(int timeout) throws IOException {
461         return isReachable(null, 0 , timeout);
462     }
463
464     /**
465      * Test whether that address is reachable. Best effort is made by the
466      * implementation to try to reach the host, but firewalls and server
467      * configuration may block requests resulting in a unreachable status
468      * while some specific ports may be accessible.
469      * A typical implementation will use ICMP ECHO REQUESTs if the
470      * privilege can be obtained, otherwise it will try to establish
471      * a TCP connection on port 7 (Echo) of the destination host.
472      * <p>
473      * The {@code network interface} and {@code ttl} parameters
474      * let the caller specify which network interface the test will go through
475      * and the maximum number of hops the packets should go through.
476      * A negative value for the {@code ttl} will result in an
477      * IllegalArgumentException being thrown.
478      * <p>
479      * The timeout value, in milliseconds, indicates the maximum amount of time
480      * the try should take. If the operation times out before getting an
481      * answer, the host is deemed unreachable. A negative value will result
482      * in an IllegalArgumentException being thrown.
483      *
484      * @param   netif   the NetworkInterface through which the
485      *                    test will be done, or null for any interface
486      * @param   ttl     the maximum numbers of hops to try or 0 for the
487      *                  default
488      * @param   timeout the time, in milliseconds, before the call aborts
489      * @throws  IllegalArgumentException if either {@code timeout}
490      *                          or {@code ttl} are negative.
491      * @return a {@code boolean}indicating if the address is reachable.
492      * @throws IOException if a network error occurs
493      * @since 1.5
494      */

495     public boolean isReachable(NetworkInterface netif, int ttl,
496                                int timeout) throws IOException {
497         if (ttl < 0)
498             throw new IllegalArgumentException("ttl can't be negative");
499         if (timeout < 0)
500             throw new IllegalArgumentException("timeout can't be negative");
501
502         return impl.isReachable(this, timeout, netif, ttl);
503     }
504
505     /**
506      * Gets the host name for this IP address.
507      *
508      * <p>If this InetAddress was created with a host name,
509      * this host name will be remembered and returned;
510      * otherwise, a reverse name lookup will be performed
511      * and the result will be returned based on the system
512      * configured name lookup service. If a lookup of the name service
513      * is required, call
514      * {@link #getCanonicalHostName() getCanonicalHostName}.
515      *
516      * <p>If there is a security manager, its
517      * {@code checkConnect} method is first called
518      * with the hostname and {@code -1}
519      * as its arguments to see if the operation is allowed.
520      * If the operation is not allowed, it will return
521      * the textual representation of the IP address.
522      *
523      * @return  the host name for this IP address, or if the operation
524      *    is not allowed by the security check, the textual
525      *    representation of the IP address.
526      *
527      * @see InetAddress#getCanonicalHostName
528      * @see SecurityManager#checkConnect
529      */

530     public String getHostName() {
531         return getHostName(true);
532     }
533
534     /**
535      * Returns the hostname for this address.
536      * If the host is equal to null, then this address refers to any
537      * of the local machine's available network addresses.
538      * this is package private so SocketPermission can make calls into
539      * here without a security check.
540      *
541      * <p>If there is a security manager, this method first
542      * calls its {@code checkConnect} method
543      * with the hostname and {@code -1}
544      * as its arguments to see if the calling code is allowed to know
545      * the hostname for this IP address, i.e., to connect to the host.
546      * If the operation is not allowed, it will return
547      * the textual representation of the IP address.
548      *
549      * @return  the host name for this IP address, or if the operation
550      *    is not allowed by the security check, the textual
551      *    representation of the IP address.
552      *
553      * @param check make security check if true
554      *
555      * @see SecurityManager#checkConnect
556      */

557     String getHostName(boolean check) {
558         if (holder().getHostName() == null) {
559             holder().hostName = InetAddress.getHostFromNameService(this, check);
560         }
561         return holder().getHostName();
562     }
563
564     /**
565      * Gets the fully qualified domain name for this IP address.
566      * Best effort method, meaning we may not be able to return
567      * the FQDN depending on the underlying system configuration.
568      *
569      * <p>If there is a security manager, this method first
570      * calls its {@code checkConnect} method
571      * with the hostname and {@code -1}
572      * as its arguments to see if the calling code is allowed to know
573      * the hostname for this IP address, i.e., to connect to the host.
574      * If the operation is not allowed, it will return
575      * the textual representation of the IP address.
576      *
577      * @return  the fully qualified domain name for this IP address,
578      *    or if the operation is not allowed by the security check,
579      *    the textual representation of the IP address.
580      *
581      * @see SecurityManager#checkConnect
582      *
583      * @since 1.4
584      */

585     public String getCanonicalHostName() {
586         if (canonicalHostName == null) {
587             canonicalHostName =
588                 InetAddress.getHostFromNameService(thistrue);
589         }
590         return canonicalHostName;
591     }
592
593     /**
594      * Returns the hostname for this address.
595      *
596      * <p>If there is a security manager, this method first
597      * calls its {@code checkConnect} method
598      * with the hostname and {@code -1}
599      * as its arguments to see if the calling code is allowed to know
600      * the hostname for this IP address, i.e., to connect to the host.
601      * If the operation is not allowed, it will return
602      * the textual representation of the IP address.
603      *
604      * @return  the host name for this IP address, or if the operation
605      *    is not allowed by the security check, the textual
606      *    representation of the IP address.
607      *
608      * @param check make security check if true
609      *
610      * @see SecurityManager#checkConnect
611      */

612     private static String getHostFromNameService(InetAddress addr, boolean check) {
613         String host = null;
614         for (NameService nameService : nameServices) {
615             try {
616                 // first lookup the hostname
617                 host = nameService.getHostByAddr(addr.getAddress());
618
619                 /* check to see if calling code is allowed to know
620                  * the hostname for this IP address, ie, connect to the host
621                  */

622                 if (check) {
623                     SecurityManager sec = System.getSecurityManager();
624                     if (sec != null) {
625                         sec.checkConnect(host, -1);
626                     }
627                 }
628
629                 /* now get all the IP addresses for this hostname,
630                  * and make sure one of them matches the original IP
631                  * address. We do this to try and prevent spoofing.
632                  */

633
634                 InetAddress[] arr = InetAddress.getAllByName0(host, check);
635                 boolean ok = false;
636
637                 if(arr != null) {
638                     for(int i = 0; !ok && i < arr.length; i++) {
639                         ok = addr.equals(arr[i]);
640                     }
641                 }
642
643                 //XXX: if it looks a spoof just return the address?
644                 if (!ok) {
645                     host = addr.getHostAddress();
646                     return host;
647                 }
648
649                 break;
650
651             } catch (SecurityException e) {
652                 host = addr.getHostAddress();
653                 break;
654             } catch (UnknownHostException e) {
655                 host = addr.getHostAddress();
656                 // let next provider resolve the hostname
657             }
658         }
659
660         return host;
661     }
662
663     /**
664      * Returns the raw IP address of this {@code InetAddress}
665      * object. The result is in network byte order: the highest order
666      * byte of the address is in {@code getAddress()[0]}.
667      *
668      * @return  the raw IP address of this object.
669      */

670     public byte[] getAddress() {
671         return null;
672     }
673
674     /**
675      * Returns the IP address string in textual presentation.
676      *
677      * @return  the raw IP address in a string format.
678      * @since   JDK1.0.2
679      */

680     public String getHostAddress() {
681         return null;
682      }
683
684     /**
685      * Returns a hashcode for this IP address.
686      *
687      * @return  a hash code value for this IP address.
688      */

689     public int hashCode() {
690         return -1;
691     }
692
693     /**
694      * Compares this object against the specified object.
695      * The result is {@code trueif and only if the argument is
696      * not {@code null} and it represents the same IP address as
697      * this object.
698      * <p>
699      * Two instances of {@code InetAddress} represent the same IP
700      * address if the length of the byte arrays returned by
701      * {@code getAddress} is the same for both, and each of the
702      * array components is the same for the byte arrays.
703      *
704      * @param   obj   the object to compare against.
705      * @return  {@code trueif the objects are the same;
706      *          {@code false} otherwise.
707      * @see     java.net.InetAddress#getAddress()
708      */

709     public boolean equals(Object obj) {
710         return false;
711     }
712
713     /**
714      * Converts this IP address to a {@code String}. The
715      * string returned is of the form: hostname / literal IP
716      * address.
717      *
718      * If the host name is unresolved, no reverse name service lookup
719      * is performed. The hostname part will be represented by an empty string.
720      *
721      * @return  a string representation of this IP address.
722      */

723     public String toString() {
724         String hostName = holder().getHostName();
725         return ((hostName != null) ? hostName : "")
726             + "/" + getHostAddress();
727     }
728
729     /*
730      * Cached addresses - our own litle nis, not!
731      */

732     private static Cache addressCache = new Cache(Cache.Type.Positive);
733
734     private static Cache negativeCache = new Cache(Cache.Type.Negative);
735
736     private static boolean addressCacheInit = false;
737
738     static InetAddress[]    unknown_array; // put THIS in cache
739
740     static InetAddressImpl  impl;
741
742     private static final HashMap<String, Void> lookupTable = new HashMap<>();
743
744     /**
745      * Represents a cache entry
746      */

747     static final class CacheEntry {
748
749         CacheEntry(InetAddress[] addresses, long expiration) {
750             this.addresses = addresses;
751             this.expiration = expiration;
752         }
753
754         InetAddress[] addresses;
755         long expiration;
756     }
757
758     /**
759      * A cache that manages entries based on a policy specified
760      * at creation time.
761      */

762     static final class Cache {
763         private LinkedHashMap<String, CacheEntry> cache;
764         private Type type;
765
766         enum Type {Positive, Negative};
767
768         /**
769          * Create cache
770          */

771         public Cache(Type type) {
772             this.type = type;
773             cache = new LinkedHashMap<String, CacheEntry>();
774         }
775
776         private int getPolicy() {
777             if (type == Type.Positive) {
778                 return InetAddressCachePolicy.get();
779             } else {
780                 return InetAddressCachePolicy.getNegative();
781             }
782         }
783
784         /**
785          * Add an entry to the cache. If there's already an
786          * entry then for this host then the entry will be
787          * replaced.
788          */

789         public Cache put(String host, InetAddress[] addresses) {
790             int policy = getPolicy();
791             if (policy == InetAddressCachePolicy.NEVER) {
792                 return this;
793             }
794
795             // purge any expired entries
796
797             if (policy != InetAddressCachePolicy.FOREVER) {
798
799                 // As we iterate in insertion order we can
800                 // terminate when a non-expired entry is found.
801                 LinkedList<String> expired = new LinkedList<>();
802                 long now = System.currentTimeMillis();
803                 for (String key : cache.keySet()) {
804                     CacheEntry entry = cache.get(key);
805
806                     if (entry.expiration >= 0 && entry.expiration < now) {
807                         expired.add(key);
808                     } else {
809                         break;
810                     }
811                 }
812
813                 for (String key : expired) {
814                     cache.remove(key);
815                 }
816             }
817
818             // create new entry and add it to the cache
819             // -- as a HashMap replaces existing entries we
820             //    don't need to explicitly check if there is
821             //    already an entry for this host.
822             long expiration;
823             if (policy == InetAddressCachePolicy.FOREVER) {
824                 expiration = -1;
825             } else {
826                 expiration = System.currentTimeMillis() + (policy * 1000);
827             }
828             CacheEntry entry = new CacheEntry(addresses, expiration);
829             cache.put(host, entry);
830             return this;
831         }
832
833         /**
834          * Query the cache for the specific host. If found then
835          * return its CacheEntry, or null if not found.
836          */

837         public CacheEntry get(String host) {
838             int policy = getPolicy();
839             if (policy == InetAddressCachePolicy.NEVER) {
840                 return null;
841             }
842             CacheEntry entry = cache.get(host);
843
844             // check if entry has expired
845             if (entry != null && policy != InetAddressCachePolicy.FOREVER) {
846                 if (entry.expiration >= 0 &&
847                     entry.expiration < System.currentTimeMillis()) {
848                     cache.remove(host);
849                     entry = null;
850                 }
851             }
852
853             return entry;
854         }
855     }
856
857     /*
858      * Initialize cache and insert anyLocalAddress into the
859      * unknown array with no expiry.
860      */

861     private static void cacheInitIfNeeded() {
862         assert Thread.holdsLock(addressCache);
863         if (addressCacheInit) {
864             return;
865         }
866         unknown_array = new InetAddress[1];
867         unknown_array[0] = impl.anyLocalAddress();
868
869         addressCache.put(impl.anyLocalAddress().getHostName(),
870                          unknown_array);
871
872         addressCacheInit = true;
873     }
874
875     /*
876      * Cache the given hostname and addresses.
877      */

878     private static void cacheAddresses(String hostname,
879                                        InetAddress[] addresses,
880                                        boolean success) {
881         hostname = hostname.toLowerCase();
882         synchronized (addressCache) {
883             cacheInitIfNeeded();
884             if (success) {
885                 addressCache.put(hostname, addresses);
886             } else {
887                 negativeCache.put(hostname, addresses);
888             }
889         }
890     }
891
892     /*
893      * Lookup hostname in cache (positive & negative cache). If
894      * found return addresses, null if not found.
895      */

896     private static InetAddress[] getCachedAddresses(String hostname) {
897         hostname = hostname.toLowerCase();
898
899         // search both positive & negative caches
900
901         synchronized (addressCache) {
902             cacheInitIfNeeded();
903
904             CacheEntry entry = addressCache.get(hostname);
905             if (entry == null) {
906                 entry = negativeCache.get(hostname);
907             }
908
909             if (entry != null) {
910                 return entry.addresses;
911             }
912         }
913
914         // not found
915         return null;
916     }
917
918     private static NameService createNSProvider(String provider) {
919         if (provider == null)
920             return null;
921
922         NameService nameService = null;
923         if (provider.equals("default")) {
924             // initialize the default name service
925             nameService = new NameService() {
926                 public InetAddress[] lookupAllHostAddr(String host)
927                     throws UnknownHostException {
928                     return impl.lookupAllHostAddr(host);
929                 }
930                 public String getHostByAddr(byte[] addr)
931                     throws UnknownHostException {
932                     return impl.getHostByAddr(addr);
933                 }
934             };
935         } else {
936             final String providerName = provider;
937             try {
938                 nameService = java.security.AccessController.doPrivileged(
939                     new java.security.PrivilegedExceptionAction<NameService>() {
940                         public NameService run() {
941                             Iterator<NameServiceDescriptor> itr =
942                                 ServiceLoader.load(NameServiceDescriptor.class)
943                                     .iterator();
944                             while (itr.hasNext()) {
945                                 NameServiceDescriptor nsd = itr.next();
946                                 if (providerName.
947                                     equalsIgnoreCase(nsd.getType()+","
948                                         +nsd.getProviderName())) {
949                                     try {
950                                         return nsd.createNameService();
951                                     } catch (Exception e) {
952                                         e.printStackTrace();
953                                         System.err.println(
954                                             "Cannot create name service:"
955                                              +providerName+": " + e);
956                                     }
957                                 }
958                             }
959
960                             return null;
961                         }
962                     }
963                 );
964             } catch (java.security.PrivilegedActionException e) {
965             }
966         }
967
968         return nameService;
969     }
970
971     static {
972         // create the impl
973         impl = InetAddressImplFactory.create();
974
975         // get name service if provided and requested
976         String provider = null;;
977         String propPrefix = "sun.net.spi.nameservice.provider.";
978         int n = 1;
979         nameServices = new ArrayList<NameService>();
980         provider = AccessController.doPrivileged(
981                 new GetPropertyAction(propPrefix + n));
982         while (provider != null) {
983             NameService ns = createNSProvider(provider);
984             if (ns != null)
985                 nameServices.add(ns);
986
987             n++;
988             provider = AccessController.doPrivileged(
989                     new GetPropertyAction(propPrefix + n));
990         }
991
992         // if not designate any name services provider,
993         // create a default one
994         if (nameServices.size() == 0) {
995             NameService ns = createNSProvider("default");
996             nameServices.add(ns);
997         }
998     }
999
1000     /**
1001      * Creates an InetAddress based on the provided host name and IP address.
1002      * No name service is checked for the validity of the address.
1003      *
1004      * <p> The host name can either be a machine name, such as
1005      * "{@code java.sun.com}", or a textual representation of its IP
1006      * address.
1007      * <p> No validity checking is done on the host name either.
1008      *
1009      * <p> If addr specifies an IPv4 address an instance of Inet4Address
1010      * will be returned; otherwise, an instance of Inet6Address
1011      * will be returned.
1012      *
1013      * <p> IPv4 address byte array must be 4 bytes long and IPv6 byte array
1014      * must be 16 bytes long
1015      *
1016      * @param host the specified host
1017      * @param addr the raw IP address in network byte order
1018      * @return  an InetAddress object created from the raw IP address.
1019      * @exception  UnknownHostException  if IP address is of illegal length
1020      * @since 1.4
1021      */

1022     public static InetAddress getByAddress(String host, byte[] addr)
1023         throws UnknownHostException {
1024         if (host != null && host.length() > 0 && host.charAt(0) == '[') {
1025             if (host.charAt(host.length()-1) == ']') {
1026                 host = host.substring(1, host.length() -1);
1027             }
1028         }
1029         if (addr != null) {
1030             if (addr.length == Inet4Address.INADDRSZ) {
1031                 return new Inet4Address(host, addr);
1032             } else if (addr.length == Inet6Address.INADDRSZ) {
1033                 byte[] newAddr
1034                     = IPAddressUtil.convertFromIPv4MappedAddress(addr);
1035                 if (newAddr != null) {
1036                     return new Inet4Address(host, newAddr);
1037                 } else {
1038                     return new Inet6Address(host, addr);
1039                 }
1040             }
1041         }
1042         throw new UnknownHostException("addr is of illegal length");
1043     }
1044
1045
1046     /**
1047      * Determines the IP address of a host, given the host's name.
1048      *
1049      * <p> The host name can either be a machine name, such as
1050      * "{@code java.sun.com}", or a textual representation of its
1051      * IP address. If a literal IP address is supplied, only the
1052      * validity of the address format is checked.
1053      *
1054      * <p> For {@code host} specified in literal IPv6 address,
1055      * either the form defined in RFC 2732 or the literal IPv6 address
1056      * format defined in RFC 2373 is accepted. IPv6 scoped addresses are also
1057      * supported. See <a href="Inet6Address.html#scoped">here</a> for a description of IPv6
1058      * scoped addresses.
1059      *
1060      * <p> If the host is {@code null} then an {@code InetAddress}
1061      * representing an address of the loopback interface is returned.
1062      * See <a href="http://www.ietf.org/rfc/rfc3330.txt">RFC&nbsp;3330</a>
1063      * section&nbsp;2 and <a href="http://www.ietf.org/rfc/rfc2373.txt">RFC&nbsp;2373</a>
1064      * section&nbsp;2.5.3. </p>
1065      *
1066      * @param      host   the specified host, or {@code null}.
1067      * @return     an IP address for the given host name.
1068      * @exception  UnknownHostException  if no IP address for the
1069      *               {@code host} could be found, or if a scope_id was specified
1070      *               for a global IPv6 address.
1071      * @exception  SecurityException if a security manager exists
1072      *             and its checkConnect method doesn't allow the operation
1073      */

1074     public static InetAddress getByName(String host)
1075         throws UnknownHostException {
1076         return InetAddress.getAllByName(host)[0];
1077     }
1078
1079     // called from deployment cache manager
1080     private static InetAddress getByName(String host, InetAddress reqAddr)
1081         throws UnknownHostException {
1082         return InetAddress.getAllByName(host, reqAddr)[0];
1083     }
1084
1085     /**
1086      * Given the name of a host, returns an array of its IP addresses,
1087      * based on the configured name service on the system.
1088      *
1089      * <p> The host name can either be a machine name, such as
1090      * "{@code java.sun.com}", or a textual representation of its IP
1091      * address. If a literal IP address is supplied, only the
1092      * validity of the address format is checked.
1093      *
1094      * <p> For {@code host} specified in <i>literal IPv6 address</i>,
1095      * either the form defined in RFC 2732 or the literal IPv6 address
1096      * format defined in RFC 2373 is accepted. A literal IPv6 address may
1097      * also be qualified by appending a scoped zone identifier or scope_id.
1098      * The syntax and usage of scope_ids is described
1099      * <a href="Inet6Address.html#scoped">here</a>.
1100      * <p> If the host is {@code null} then an {@code InetAddress}
1101      * representing an address of the loopback interface is returned.
1102      * See <a href="http://www.ietf.org/rfc/rfc3330.txt">RFC&nbsp;3330</a>
1103      * section&nbsp;2 and <a href="http://www.ietf.org/rfc/rfc2373.txt">RFC&nbsp;2373</a>
1104      * section&nbsp;2.5.3. </p>
1105      *
1106      * <p> If there is a security manager and {@code host} is not
1107      * null and {@code host.length() } is not equal to zero, the
1108      * security manager's
1109      * {@code checkConnect} method is called
1110      * with the hostname and {@code -1}
1111      * as its arguments to see if the operation is allowed.
1112      *
1113      * @param      host   the name of the host, or {@code null}.
1114      * @return     an array of all the IP addresses for a given host name.
1115      *
1116      * @exception  UnknownHostException  if no IP address for the
1117      *               {@code host} could be found, or if a scope_id was specified
1118      *               for a global IPv6 address.
1119      * @exception  SecurityException  if a security manager exists and its
1120      *               {@code checkConnect} method doesn't allow the operation.
1121      *
1122      * @see SecurityManager#checkConnect
1123      */

1124     public static InetAddress[] getAllByName(String host)
1125         throws UnknownHostException {
1126         return getAllByName(host, null);
1127     }
1128
1129     private static InetAddress[] getAllByName(String host, InetAddress reqAddr)
1130         throws UnknownHostException {
1131
1132         if (host == null || host.length() == 0) {
1133             InetAddress[] ret = new InetAddress[1];
1134             ret[0] = impl.loopbackAddress();
1135             return ret;
1136         }
1137
1138         boolean ipv6Expected = false;
1139         if (host.charAt(0) == '[') {
1140             // This is supposed to be an IPv6 literal
1141             if (host.length() > 2 && host.charAt(host.length()-1) == ']') {
1142                 host = host.substring(1, host.length() -1);
1143                 ipv6Expected = true;
1144             } else {
1145                 // This was supposed to be a IPv6 address, but it's not!
1146                 throw new UnknownHostException(host + ": invalid IPv6 address");
1147             }
1148         }
1149
1150         // if host is an IP address, we won't do further lookup
1151         if (Character.digit(host.charAt(0), 16) != -1
1152             || (host.charAt(0) == ':')) {
1153             byte[] addr = null;
1154             int numericZone = -1;
1155             String ifname = null;
1156             // see if it is IPv4 address
1157             addr = IPAddressUtil.textToNumericFormatV4(host);
1158             if (addr == null) {
1159                 // This is supposed to be an IPv6 literal
1160                 // Check if a numeric or string zone id is present
1161                 int pos;
1162                 if ((pos=host.indexOf ("%")) != -1) {
1163                     numericZone = checkNumericZone (host);
1164                     if (numericZone == -1) { /* remainder of string must be an ifname */
1165                         ifname = host.substring (pos+1);
1166                     }
1167                 }
1168                 if ((addr = IPAddressUtil.textToNumericFormatV6(host)) == null && host.contains(":")) {
1169                     throw new UnknownHostException(host + ": invalid IPv6 address");
1170                 }
1171             } else if (ipv6Expected) {
1172                 // Means an IPv4 litteral between brackets!
1173                 throw new UnknownHostException("["+host+"]");
1174             }
1175             InetAddress[] ret = new InetAddress[1];
1176             if(addr != null) {
1177                 if (addr.length == Inet4Address.INADDRSZ) {
1178                     ret[0] = new Inet4Address(null, addr);
1179                 } else {
1180                     if (ifname != null) {
1181                         ret[0] = new Inet6Address(null, addr, ifname);
1182                     } else {
1183                         ret[0] = new Inet6Address(null, addr, numericZone);
1184                     }
1185                 }
1186                 return ret;
1187             }
1188         } else if (ipv6Expected) {
1189             // We were expecting an IPv6 Litteral, but got something else
1190             throw new UnknownHostException("["+host+"]");
1191         }
1192         return getAllByName0(host, reqAddr, true);
1193     }
1194
1195     /**
1196      * Returns the loopback address.
1197      * <p>
1198      * The InetAddress returned will represent the IPv4
1199      * loopback address, 127.0.0.1, or the IPv6 loopback
1200      * address, ::1. The IPv4 loopback address returned
1201      * is only one of many in the form 127.*.*.*
1202      *
1203      * @return  the InetAddress loopback instance.
1204      * @since 1.7
1205      */

1206     public static InetAddress getLoopbackAddress() {
1207         return impl.loopbackAddress();
1208     }
1209
1210
1211     /**
1212      * check if the literal address string has %nn appended
1213      * returns -1 if not, or the numeric value otherwise.
1214      *
1215      * %nn may also be a string that represents the displayName of
1216      * a currently available NetworkInterface.
1217      */

1218     private static int checkNumericZone (String s) throws UnknownHostException {
1219         int percent = s.indexOf ('%');
1220         int slen = s.length();
1221         int digit, zone=0;
1222         if (percent == -1) {
1223             return -1;
1224         }
1225         for (int i=percent+1; i<slen; i++) {
1226             char c = s.charAt(i);
1227             if (c == ']') {
1228                 if (i == percent+1) {
1229                     /* empty per-cent field */
1230                     return -1;
1231                 }
1232                 break;
1233             }
1234             if ((digit = Character.digit (c, 10)) < 0) {
1235                 return -1;
1236             }
1237             zone = (zone * 10) + digit;
1238         }
1239         return zone;
1240     }
1241
1242     private static InetAddress[] getAllByName0 (String host)
1243         throws UnknownHostException
1244     {
1245         return getAllByName0(host, true);
1246     }
1247
1248     /**
1249      * package private so SocketPermission can call it
1250      */

1251     static InetAddress[] getAllByName0 (String host, boolean check)
1252         throws UnknownHostException  {
1253         return getAllByName0 (host, null, check);
1254     }
1255
1256     private static InetAddress[] getAllByName0 (String host, InetAddress reqAddr, boolean check)
1257         throws UnknownHostException  {
1258
1259         /* If it gets here it is presumed to be a hostname */
1260         /* Cache.get can returnnull, unknownAddress, or InetAddress[] */
1261
1262         /* make sure the connection to the host is allowed, before we
1263          * give out a hostname
1264          */

1265         if (check) {
1266             SecurityManager security = System.getSecurityManager();
1267             if (security != null) {
1268                 security.checkConnect(host, -1);
1269             }
1270         }
1271
1272         InetAddress[] addresses = getCachedAddresses(host);
1273
1274         /* If no entry in cache, then do the host lookup */
1275         if (addresses == null) {
1276             addresses = getAddressesFromNameService(host, reqAddr);
1277         }
1278
1279         if (addresses == unknown_array)
1280             throw new UnknownHostException(host);
1281
1282         return addresses.clone();
1283     }
1284
1285     private static InetAddress[] getAddressesFromNameService(String host, InetAddress reqAddr)
1286         throws UnknownHostException
1287     {
1288         InetAddress[] addresses = null;
1289         boolean success = false;
1290         UnknownHostException ex = null;
1291
1292         // Check whether the host is in the lookupTable.
1293         // 1) If the host isn't in the lookupTable when
1294         //    checkLookupTable() is called, checkLookupTable()
1295         //    would add the host in the lookupTable and
1296         //    return null. So we will do the lookup.
1297         // 2) If the host is in the lookupTable when
1298         //    checkLookupTable() is called, the current thread
1299         //    would be blocked until the host is removed
1300         //    from the lookupTable. Then this thread
1301         //    should try to look up the addressCache.
1302         //     i) if it found the addresses in the
1303         //        addressCache, checkLookupTable()  would
1304         //        return the addresses.
1305         //     ii) if it didn't find the addresses in the
1306         //         addressCache for any reason,
1307         //         it should add the host in the
1308         //         lookupTable and return null so the
1309         //         following code would do  a lookup itself.
1310         if ((addresses = checkLookupTable(host)) == null) {
1311             try {
1312                 // This is the first thread which looks up the addresses
1313                 // this host or the cache entry for this host has been
1314                 // expired so this thread should do the lookup.
1315                 for (NameService nameService : nameServices) {
1316                     try {
1317                         /*
1318                          * Do not put the call to lookup() inside the
1319                          * constructor.  if you do you will still be
1320                          * allocating space when the lookup fails.
1321                          */

1322
1323                         addresses = nameService.lookupAllHostAddr(host);
1324                         success = true;
1325                         break;
1326                     } catch (UnknownHostException uhe) {
1327                         if (host.equalsIgnoreCase("localhost")) {
1328                             InetAddress[] local = new InetAddress[] { impl.loopbackAddress() };
1329                             addresses = local;
1330                             success = true;
1331                             break;
1332                         }
1333                         else {
1334                             addresses = unknown_array;
1335                             success = false;
1336                             ex = uhe;
1337                         }
1338                     }
1339                 }
1340
1341                 // More to do?
1342                 if (reqAddr != null && addresses.length > 1 && !addresses[0].equals(reqAddr)) {
1343                     // Find it?
1344                     int i = 1;
1345                     for (; i < addresses.length; i++) {
1346                         if (addresses[i].equals(reqAddr)) {
1347                             break;
1348                         }
1349                     }
1350                     // Rotate
1351                     if (i < addresses.length) {
1352                         InetAddress tmp, tmp2 = reqAddr;
1353                         for (int j = 0; j < i; j++) {
1354                             tmp = addresses[j];
1355                             addresses[j] = tmp2;
1356                             tmp2 = tmp;
1357                         }
1358                         addresses[i] = tmp2;
1359                     }
1360                 }
1361                 // Cache the address.
1362                 cacheAddresses(host, addresses, success);
1363
1364                 if (!success && ex != null)
1365                     throw ex;
1366
1367             } finally {
1368                 // Delete host from the lookupTable and notify
1369                 // all threads waiting on the lookupTable monitor.
1370                 updateLookupTable(host);
1371             }
1372         }
1373
1374         return addresses;
1375     }
1376
1377
1378     private static InetAddress[] checkLookupTable(String host) {
1379         synchronized (lookupTable) {
1380             // If the host isn't in the lookupTable, add it in the
1381             // lookuptable and return null. The caller should do
1382             // the lookup.
1383             if (lookupTable.containsKey(host) == false) {
1384                 lookupTable.put(host, null);
1385                 return null;
1386             }
1387
1388             // If the host is in the lookupTable, it means that another
1389             // thread is trying to look up the addresses of this host.
1390             // This thread should wait.
1391             while (lookupTable.containsKey(host)) {
1392                 try {
1393                     lookupTable.wait();
1394                 } catch (InterruptedException e) {
1395                 }
1396             }
1397         }
1398
1399         // The other thread has finished looking up the addresses of
1400         // the host. This thread should retry to get the addresses
1401         // from the addressCache. If it doesn't get the addresses from
1402         // the cache, it will try to look up the addresses itself.
1403         InetAddress[] addresses = getCachedAddresses(host);
1404         if (addresses == null) {
1405             synchronized (lookupTable) {
1406                 lookupTable.put(host, null);
1407                 return null;
1408             }
1409         }
1410
1411         return addresses;
1412     }
1413
1414     private static void updateLookupTable(String host) {
1415         synchronized (lookupTable) {
1416             lookupTable.remove(host);
1417             lookupTable.notifyAll();
1418         }
1419     }
1420
1421     /**
1422      * Returns an {@code InetAddress} object given the raw IP address .
1423      * The argument is in network byte order: the highest order
1424      * byte of the address is in {@code getAddress()[0]}.
1425      *
1426      * <p> This method doesn't block, i.e. no reverse name service lookup
1427      * is performed.
1428      *
1429      * <p> IPv4 address byte array must be 4 bytes long and IPv6 byte array
1430      * must be 16 bytes long
1431      *
1432      * @param addr the raw IP address in network byte order
1433      * @return  an InetAddress object created from the raw IP address.
1434      * @exception  UnknownHostException  if IP address is of illegal length
1435      * @since 1.4
1436      */

1437     public static InetAddress getByAddress(byte[] addr)
1438         throws UnknownHostException {
1439         return getByAddress(null, addr);
1440     }
1441
1442     private static InetAddress cachedLocalHost = null;
1443     private static long cacheTime = 0;
1444     private static final long maxCacheTime = 5000L;
1445     private static final Object cacheLock = new Object();
1446
1447     /**
1448      * Returns the address of the local host. This is achieved by retrieving
1449      * the name of the host from the system, then resolving that name into
1450      * an {@code InetAddress}.
1451      *
1452      * <P>Note: The resolved address may be cached for a short period of time.
1453      * </P>
1454      *
1455      * <p>If there is a security manager, its
1456      * {@code checkConnect} method is called
1457      * with the local host name and {@code -1}
1458      * as its arguments to see if the operation is allowed.
1459      * If the operation is not allowed, an InetAddress representing
1460      * the loopback address is returned.
1461      *
1462      * @return     the address of the local host.
1463      *
1464      * @exception  UnknownHostException  if the local host name could not
1465      *             be resolved into an address.
1466      *
1467      * @see SecurityManager#checkConnect
1468      * @see java.net.InetAddress#getByName(java.lang.String)
1469      */

1470     public static InetAddress getLocalHost() throws UnknownHostException {
1471
1472         SecurityManager security = System.getSecurityManager();
1473         try {
1474             String local = impl.getLocalHostName();
1475
1476             if (security != null) {
1477                 security.checkConnect(local, -1);
1478             }
1479
1480             if (local.equals("localhost")) {
1481                 return impl.loopbackAddress();
1482             }
1483
1484             InetAddress ret = null;
1485             synchronized (cacheLock) {
1486                 long now = System.currentTimeMillis();
1487                 if (cachedLocalHost != null) {
1488                     if ((now - cacheTime) < maxCacheTime) // Less than 5s old?
1489                         ret = cachedLocalHost;
1490                     else
1491                         cachedLocalHost = null;
1492                 }
1493
1494                 // we are calling getAddressesFromNameService directly
1495                 // to avoid getting localHost from cache
1496                 if (ret == null) {
1497                     InetAddress[] localAddrs;
1498                     try {
1499                         localAddrs =
1500                             InetAddress.getAddressesFromNameService(local, null);
1501                     } catch (UnknownHostException uhe) {
1502                         // Rethrow with a more informative error message.
1503                         UnknownHostException uhe2 =
1504                             new UnknownHostException(local + ": " +
1505                                                      uhe.getMessage());
1506                         uhe2.initCause(uhe);
1507                         throw uhe2;
1508                     }
1509                     cachedLocalHost = localAddrs[0];
1510                     cacheTime = now;
1511                     ret = localAddrs[0];
1512                 }
1513             }
1514             return ret;
1515         } catch (java.lang.SecurityException e) {
1516             return impl.loopbackAddress();
1517         }
1518     }
1519
1520     /**
1521      * Perform class load-time initializations.
1522      */

1523     private static native void init();
1524
1525
1526     /*
1527      * Returns the InetAddress representing anyLocalAddress
1528      * (typically 0.0.0.0 or ::0)
1529      */

1530     static InetAddress anyLocalAddress() {
1531         return impl.anyLocalAddress();
1532     }
1533
1534     /*
1535      * Load and instantiate an underlying impl class
1536      */

1537     static InetAddressImpl loadImpl(String implName) {
1538         Object impl = null;
1539
1540         /*
1541          * Property "impl.prefix" will be prepended to the classname
1542          * of the implementation object we instantiate, to which we
1543          * delegate the real work (like native methods).  This
1544          * property can vary across implementations of the java.
1545          * classes.  The default is an empty String "".
1546          */

1547         String prefix = AccessController.doPrivileged(
1548                       new GetPropertyAction("impl.prefix"""));
1549         try {
1550             impl = Class.forName("java.net." + prefix + implName).newInstance();
1551         } catch (ClassNotFoundException e) {
1552             System.err.println("Class not found: java.net." + prefix +
1553                                implName + ":\ncheck impl.prefix property " +
1554                                "in your properties file.");
1555         } catch (InstantiationException e) {
1556             System.err.println("Could not instantiate: java.net." + prefix +
1557                                implName + ":\ncheck impl.prefix property " +
1558                                "in your properties file.");
1559         } catch (IllegalAccessException e) {
1560             System.err.println("Cannot access class: java.net." + prefix +
1561                                implName + ":\ncheck impl.prefix property " +
1562                                "in your properties file.");
1563         }
1564
1565         if (impl == null) {
1566             try {
1567                 impl = Class.forName(implName).newInstance();
1568             } catch (Exception e) {
1569                 throw new Error("System property impl.prefix incorrect");
1570             }
1571         }
1572
1573         return (InetAddressImpl) impl;
1574     }
1575
1576     private void readObjectNoData (ObjectInputStream s) throws
1577                          IOException, ClassNotFoundException {
1578         if (getClass().getClassLoader() != null) {
1579             throw new SecurityException ("invalid address type");
1580         }
1581     }
1582
1583     private static final long FIELDS_OFFSET;
1584     private static final sun.misc.Unsafe UNSAFE;
1585
1586     static {
1587         try {
1588             sun.misc.Unsafe unsafe = sun.misc.Unsafe.getUnsafe();
1589             FIELDS_OFFSET = unsafe.objectFieldOffset(
1590                 InetAddress.class.getDeclaredField("holder")
1591             );
1592             UNSAFE = unsafe;
1593         } catch (ReflectiveOperationException e) {
1594             throw new Error(e);
1595         }
1596     }
1597
1598     private void readObject (ObjectInputStream s) throws
1599                          IOException, ClassNotFoundException {
1600         if (getClass().getClassLoader() != null) {
1601             throw new SecurityException ("invalid address type");
1602         }
1603         GetField gf = s.readFields();
1604         String host = (String)gf.get("hostName"null);
1605         int address= gf.get("address", 0);
1606         int family= gf.get("family", 0);
1607         InetAddressHolder h = new InetAddressHolder(host, address, family);
1608         UNSAFE.putObject(this, FIELDS_OFFSET, h);
1609     }
1610
1611     /* needed because the serializable fields no longer exist */
1612
1613     /**
1614      * @serialField hostName String
1615      * @serialField address int
1616      * @serialField family int
1617      */

1618     private static final ObjectStreamField[] serialPersistentFields = {
1619         new ObjectStreamField("hostName", String.class),
1620         new ObjectStreamField("address"int.class),
1621         new ObjectStreamField("family"int.class),
1622     };
1623
1624     private void writeObject (ObjectOutputStream s) throws
1625                         IOException {
1626         if (getClass().getClassLoader() != null) {
1627             throw new SecurityException ("invalid address type");
1628         }
1629         PutField pf = s.putFields();
1630         pf.put("hostName", holder().getHostName());
1631         pf.put("address", holder().getAddress());
1632         pf.put("family", holder().getFamily());
1633         s.writeFields();
1634     }
1635 }
1636
1637 /*
1638  * Simple factory to create the impl
1639  */

1640 class InetAddressImplFactory {
1641
1642     static InetAddressImpl create() {
1643         return InetAddress.loadImpl(isIPv6Supported() ?
1644                                     "Inet6AddressImpl" : "Inet4AddressImpl");
1645     }
1646
1647     static native boolean isIPv6Supported();
1648 }
1649
Powered by JavaMelody