InetAddress.java revision 0917c4a9d5d0115950450cdd0bb46e43a48da5db
1/*
2 *  Licensed to the Apache Software Foundation (ASF) under one or more
3 *  contributor license agreements.  See the NOTICE file distributed with
4 *  this work for additional information regarding copyright ownership.
5 *  The ASF licenses this file to You under the Apache License, Version 2.0
6 *  (the "License"); you may not use this file except in compliance with
7 *  the License.  You may obtain a copy of the License at
8 *
9 *     http://www.apache.org/licenses/LICENSE-2.0
10 *
11 *  Unless required by applicable law or agreed to in writing, software
12 *  distributed under the License is distributed on an "AS IS" BASIS,
13 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 *  See the License for the specific language governing permissions and
15 *  limitations under the License.
16 */
17
18package java.net;
19
20import dalvik.system.BlockGuard;
21import java.io.FileDescriptor;
22import java.io.IOException;
23import java.io.ObjectInputStream;
24import java.io.ObjectOutputStream;
25import java.io.ObjectStreamException;
26import java.io.ObjectStreamField;
27import java.io.Serializable;
28import java.security.AccessController;
29import java.util.Arrays;
30import java.util.Collections;
31import java.util.Comparator;
32import java.util.Enumeration;
33import java.util.List;
34import org.apache.harmony.luni.platform.INetworkSystem;
35import org.apache.harmony.luni.platform.Platform;
36import org.apache.harmony.luni.util.PriviAction;
37
38/**
39 * An Internet Protocol (IP) address. This can be either an IPv4 address or an IPv6 address, and
40 * in practice you'll have an instance of either {@code Inet4Address} or {@code Inet6Address} (this
41 * class cannot be instantiated directly). Most code does not need to distinguish between the two
42 * families, and should use {@code InetAddress}.
43 *
44 * <p>An {@code InetAddress} may have a hostname (accessible via {@code getHostName}), but may not,
45 * depending on how the {@code InetAddress} was created.
46 *
47 * <h4>IPv4 numeric address formats</h4>
48 * <p>The {@code getAllByName} method accepts IPv4 addresses in the following forms:
49 * <ul>
50 * <li>{@code "1.2.3.4"} - 1.2.3.4
51 * <li>{@code "1.2.3"} - 1.2.0.3
52 * <li>{@code "1.2"} - 1.0.0.2
53 * <li>{@code "16909060"} - 1.2.3.4
54 * </ul>
55 * <p>In the first three cases, each number is treated as an 8-bit value between 0 and 255.
56 * In the fourth case, the single number is treated as a 32-bit value representing the entire
57 * address.
58 * <p>Note that each numeric part can be expressed in decimal (as above) or hex. For example,
59 * {@code "0x01020304"} is equivalent to 1.2.3.4 and {@code "0xa.0xb.0xc.0xd"} is equivalent
60 * to 10.11.12.13.
61 *
62 * <p>Typically, only the four-dot decimal form ({@code "1.2.3.4"}) is ever used. Any method that
63 * <i>returns</i> a textual numeric address will use four-dot decimal form.
64 *
65 * <h4>IPv6 numeric address formats</h4>
66 * <p>The {@code getAllByName} method accepts IPv6 addresses in the following forms (this text
67 * comes from <a href="http://www.ietf.org/rfc/rfc2373.txt">RFC 2373</a>, which you should consult
68 * for full details of IPv6 addressing):
69 * <ul>
70 * <li><p>The preferred form is {@code x:x:x:x:x:x:x:x}, where the 'x's are the
71 * hexadecimal values of the eight 16-bit pieces of the address.
72 * Note that it is not necessary to write the leading zeros in an
73 * individual field, but there must be at least one numeral in every
74 * field (except for the case described in the next bullet).
75 * Examples:
76 * <pre>
77 *     FEDC:BA98:7654:3210:FEDC:BA98:7654:3210
78 *     1080:0:0:0:8:800:200C:417A</pre>
79 * </li>
80 * <li>Due to some methods of allocating certain styles of IPv6
81 * addresses, it will be common for addresses to contain long strings
82 * of zero bits.  In order to make writing addresses containing zero
83 * bits easier a special syntax is available to compress the zeros.
84 * The use of "::" indicates multiple groups of 16-bits of zeros.
85 * The "::" can only appear once in an address.  The "::" can also be
86 * used to compress the leading and/or trailing zeros in an address.
87 *
88 * For example the following addresses:
89 * <pre>
90 *     1080:0:0:0:8:800:200C:417A  a unicast address
91 *     FF01:0:0:0:0:0:0:101        a multicast address
92 *     0:0:0:0:0:0:0:1             the loopback address
93 *     0:0:0:0:0:0:0:0             the unspecified addresses</pre>
94 * may be represented as:
95 * <pre>
96 *     1080::8:800:200C:417A       a unicast address
97 *     FF01::101                   a multicast address
98 *     ::1                         the loopback address
99 *     ::                          the unspecified addresses</pre>
100 * </li>
101 * <li><p>An alternative form that is sometimes more convenient when dealing
102 * with a mixed environment of IPv4 and IPv6 nodes is
103 * {@code x:x:x:x:x:x:d.d.d.d}, where the 'x's are the hexadecimal values of
104 * the six high-order 16-bit pieces of the address, and the 'd's are
105 * the decimal values of the four low-order 8-bit pieces of the
106 * address (standard IPv4 representation).  Examples:
107 * <pre>
108 *     0:0:0:0:0:0:13.1.68.3
109 *     0:0:0:0:0:FFFF:129.144.52.38</pre>
110 * or in compressed form:
111 * <pre>
112 *     ::13.1.68.3
113 *     ::FFFF:129.144.52.38</pre>
114 * </li>
115 * </ul>
116 * <p>Scopes are given using a trailing {@code %} followed by the scope id, as in
117 * {@code 1080::8:800:200C:417A%2} or {@code 1080::8:800:200C:417A%en0}.
118 * See <a href="https://www.ietf.org/rfc/rfc4007.txt">RFC 4007</a> for more on IPv6's scoped
119 * address architecture.
120 *
121 * <h4>DNS caching</h4>
122 * <p>On Android, addresses are cached for 600 seconds (10 minutes) by default. Failed lookups are
123 * cached for 10 seconds. The underlying C library or OS may cache for longer, but you can control
124 * the Java-level caching with the usual {@code "networkaddress.cache.ttl"} and
125 * {@code "networkaddress.cache.negative.ttl"} system properties. These are parsed as integer
126 * numbers of seconds, where the special value 0 means "don't cache" and -1 means "cache forever".
127 *
128 * <p>Note also that on Android &ndash; unlike the RI &ndash; the cache is not unbounded. The
129 * current implementation caches around 512 entries, removed on a least-recently-used basis.
130 * (Obviously, you should not rely on these details.)
131 *
132 * @see Inet4Address
133 * @see Inet6Address
134 */
135public class InetAddress implements Serializable {
136    /** Our Java-side DNS cache. */
137    private static final AddressCache addressCache = new AddressCache();
138
139    private final static INetworkSystem NETIMPL = Platform.getNetworkSystem();
140
141    private static final String ERRMSG_CONNECTION_REFUSED = "Connection refused";
142
143    private static final long serialVersionUID = 3286316764910316507L;
144
145    String hostName;
146
147    private static class WaitReachable {
148    }
149
150    private transient Object waitReachable = new WaitReachable();
151
152    private boolean reached;
153
154    private int addrCount;
155
156    int family = 0;
157    static final int AF_INET = 2;
158    static final int AF_INET6 = 10;
159
160    byte[] ipaddress;
161
162    /**
163     * Constructs an {@code InetAddress}.
164     *
165     * Note: this constructor should not be used. Creating an InetAddress
166     * without specifying whether it's an IPv4 or IPv6 address does not make
167     * sense, because subsequent code cannot know which of of the subclasses'
168     * methods need to be called to implement a given InetAddress method. The
169     * proper way to create an InetAddress is to call new Inet4Address or
170     * Inet6Address or to use one of the static methods that return
171     * InetAddresses (e.g., getByAddress). That is why the API does not have
172     * public constructors for any of these classes.
173     */
174    InetAddress() {}
175
176    /**
177     * Compares this {@code InetAddress} instance against the specified address
178     * in {@code obj}. Two addresses are equal if their address byte arrays have
179     * the same length and if the bytes in the arrays are equal.
180     *
181     * @param obj
182     *            the object to be tested for equality.
183     * @return {@code true} if both objects are equal, {@code false} otherwise.
184     */
185    @Override
186    public boolean equals(Object obj) {
187        if (!(obj instanceof InetAddress)) {
188            return false;
189        }
190        return Arrays.equals(this.ipaddress, ((InetAddress) obj).ipaddress);
191    }
192
193    /**
194     * Returns the IP address represented by this {@code InetAddress} instance
195     * as a byte array. The elements are in network order (the highest order
196     * address byte is in the zeroth element).
197     *
198     * @return the address in form of a byte array.
199     */
200    public byte[] getAddress() {
201        return ipaddress.clone();
202    }
203
204    static final Comparator<byte[]> SHORTEST_FIRST = new Comparator<byte[]>() {
205        public int compare(byte[] a1, byte[] a2) {
206            return a1.length - a2.length;
207        }
208    };
209
210    /**
211     * Converts an array of byte arrays representing raw IP addresses of a host
212     * to an array of InetAddress objects, sorting to respect the value of the
213     * system property {@code "java.net.preferIPv6Addresses"}.
214     *
215     * @param rawAddresses the raw addresses to convert.
216     * @param hostName the hostname corresponding to the IP address.
217     * @return the corresponding InetAddresses, appropriately sorted.
218     */
219    static InetAddress[] bytesToInetAddresses(byte[][] rawAddresses, String hostName) {
220        // If we prefer IPv4, ignore the RFC3484 ordering we get from getaddrinfo
221        // and always put IPv4 addresses first. Arrays.sort() is stable, so the
222        // internal ordering will not be changed.
223        if (!preferIPv6Addresses()) {
224            Arrays.sort(rawAddresses, SHORTEST_FIRST);
225        }
226
227        // Convert the byte arrays to InetAddresses.
228        InetAddress[] returnedAddresses = new InetAddress[rawAddresses.length];
229        for (int i = 0; i < rawAddresses.length; i++) {
230            byte[] rawAddress = rawAddresses[i];
231            if (rawAddress.length == 16) {
232                returnedAddresses[i] = new Inet6Address(rawAddress, hostName);
233            } else if (rawAddress.length == 4) {
234                returnedAddresses[i] = new Inet4Address(rawAddress, hostName);
235            } else {
236              // Cannot happen, because the underlying code only returns
237              // addresses that are 4 or 16 bytes long.
238              throw new AssertionError("Impossible address length " +
239                                       rawAddress.length);
240            }
241        }
242        return returnedAddresses;
243    }
244
245    /**
246     * Gets all IP addresses associated with the given {@code host} identified
247     * by name or literal IP address. The IP address is resolved by the
248     * configured name service. If the host name is empty or {@code null} an
249     * {@code UnknownHostException} is thrown. If the host name is a literal IP
250     * address string an array with the corresponding single {@code InetAddress}
251     * is returned.
252     *
253     * @param host the hostname or literal IP string to be resolved.
254     * @return the array of addresses associated with the specified host.
255     * @throws UnknownHostException if the address lookup fails.
256     */
257    public static InetAddress[] getAllByName(String host) throws UnknownHostException {
258        return getAllByNameImpl(host).clone();
259    }
260
261    /**
262     * Returns the InetAddresses for {@code host}. The returned array is shared
263     * and must be cloned before it is returned to application code.
264     */
265    static InetAddress[] getAllByNameImpl(String host) throws UnknownHostException {
266        if (host == null || host.isEmpty()) {
267            if (preferIPv6Addresses()) {
268                return new InetAddress[] { Inet6Address.LOOPBACK, Inet4Address.LOOPBACK };
269            } else {
270                return new InetAddress[] { Inet4Address.LOOPBACK, Inet6Address.LOOPBACK };
271            }
272        }
273
274        // Special-case "0" for legacy IPv4 applications.
275        if (host.equals("0")) {
276            return new InetAddress[] { Inet4Address.ANY };
277        }
278
279        try {
280            byte[] hBytes = ipStringToByteArray(host);
281            if (hBytes.length == 4) {
282                return (new InetAddress[] { new Inet4Address(hBytes) });
283            } else if (hBytes.length == 16) {
284                return (new InetAddress[] { new Inet6Address(hBytes) });
285            } else {
286                throw new UnknownHostException(wrongAddressLength());
287            }
288        } catch (UnknownHostException e) {
289        }
290
291        SecurityManager security = System.getSecurityManager();
292        if (security != null) {
293            security.checkConnect(host, -1);
294        }
295
296        return lookupHostByName(host);
297    }
298
299    private static native String byteArrayToIpString(byte[] address);
300
301    static native byte[] ipStringToByteArray(String address) throws UnknownHostException;
302
303    private static String wrongAddressLength() {
304        return "Invalid IP Address is neither 4 or 16 bytes";
305    }
306
307    static boolean preferIPv6Addresses() {
308        String propertyName = "java.net.preferIPv6Addresses";
309        String propertyValue = AccessController.doPrivileged(new PriviAction<String>(propertyName));
310        return Boolean.getBoolean(propertyValue);
311    }
312
313    /**
314     * Returns the address of a host according to the given host string name
315     * {@code host}. The host string may be either a machine name or a dotted
316     * string IP address. If the latter, the {@code hostName} field is
317     * determined upon demand. {@code host} can be {@code null} which means that
318     * an address of the loopback interface is returned.
319     *
320     * @param host
321     *            the hostName to be resolved to an address or {@code null}.
322     * @return the {@code InetAddress} instance representing the host.
323     * @throws UnknownHostException
324     *             if the address lookup fails.
325     */
326    public static InetAddress getByName(String host) throws UnknownHostException {
327        return getAllByNameImpl(host)[0];
328    }
329
330    /**
331     * Gets the textual representation of this IP address.
332     *
333     * @return the textual representation of host's IP address.
334     */
335    public String getHostAddress() {
336        return byteArrayToIpString(ipaddress);
337    }
338
339    /**
340     * Gets the host name of this IP address. If the IP address could not be
341     * resolved, the textual representation in a dotted-quad-notation is
342     * returned.
343     *
344     * @return the corresponding string name of this IP address.
345     */
346    public String getHostName() {
347        try {
348            if (hostName == null) {
349                int address = 0;
350                if (ipaddress.length == 4) {
351                    address = bytesToInt(ipaddress, 0);
352                    if (address == 0) {
353                        return hostName = byteArrayToIpString(ipaddress);
354                    }
355                }
356                hostName = getHostByAddrImpl(ipaddress).hostName;
357                if (hostName.equals("localhost") && ipaddress.length == 4
358                        && address != 0x7f000001) {
359                    return hostName = byteArrayToIpString(ipaddress);
360                }
361            }
362        } catch (UnknownHostException e) {
363            return hostName = byteArrayToIpString(ipaddress);
364        }
365        SecurityManager security = System.getSecurityManager();
366        try {
367            // Only check host names, not addresses
368            if (security != null && isHostName(hostName)) {
369                security.checkConnect(hostName, -1);
370            }
371        } catch (SecurityException e) {
372            return byteArrayToIpString(ipaddress);
373        }
374        return hostName;
375    }
376
377    /**
378     * Gets the fully qualified domain name for the host associated with this IP
379     * address. If a security manager is set, it is checked if the method caller
380     * is allowed to get the hostname. Otherwise, the textual representation in
381     * a dotted-quad-notation is returned.
382     *
383     * @return the fully qualified domain name of this IP address.
384     */
385    public String getCanonicalHostName() {
386        String canonicalName;
387        try {
388            int address = 0;
389            if (ipaddress.length == 4) {
390                address = bytesToInt(ipaddress, 0);
391                if (address == 0) {
392                    return byteArrayToIpString(ipaddress);
393                }
394            }
395            canonicalName = getHostByAddrImpl(ipaddress).hostName;
396        } catch (UnknownHostException e) {
397            return byteArrayToIpString(ipaddress);
398        }
399        SecurityManager security = System.getSecurityManager();
400        try {
401            // Only check host names, not addresses
402            if (security != null && isHostName(canonicalName)) {
403                security.checkConnect(canonicalName, -1);
404            }
405        } catch (SecurityException e) {
406            return byteArrayToIpString(ipaddress);
407        }
408        return canonicalName;
409    }
410
411    /**
412     * Returns an {@code InetAddress} for the local host if possible, or the
413     * loopback address otherwise. This method works by getting the hostname,
414     * performing a DNS lookup, and then taking the first returned address.
415     * For devices with multiple network interfaces and/or multiple addresses
416     * per interface, this does not necessarily return the {@code InetAddress}
417     * you want.
418     *
419     * <p>Multiple interface/address configurations were relatively rare
420     * when this API was designed, but multiple interfaces are the default for
421     * modern mobile devices (with separate wifi and radio interfaces), and
422     * the need to support both IPv4 and IPv6 has made multiple addresses
423     * commonplace. New code should thus avoid this method except where it's
424     * basically being used to get a loopback address or equivalent.
425     *
426     * <p>There are two main ways to get a more specific answer:
427     * <ul>
428     * <li>If you have a connected socket, you should probably use
429     * {@link Socket#getLocalAddress} instead: that will give you the address
430     * that's actually in use for that connection. (It's not possible to ask
431     * the question "what local address would a connection to a given remote
432     * address use?"; you have to actually make the connection and see.)</li>
433     * <li>For other use cases, see {@link NetworkInterface}, which lets you
434     * enumerate all available network interfaces and their addresses.</li>
435     * </ul>
436     *
437     * <p>Note that if the host doesn't have a hostname set&nbsp;&ndash; as
438     * Android devices typically don't&nbsp;&ndash; this method will
439     * effectively return the loopback address, albeit by getting the name
440     * {@code localhost} and then doing a lookup to translate that to
441     * {@code 127.0.0.1}.
442     *
443     * @return an {@code InetAddress} representing the local host, or the
444     * loopback address.
445     * @throws UnknownHostException
446     *             if the address lookup fails.
447     */
448    public static InetAddress getLocalHost() throws UnknownHostException {
449        String host = gethostname();
450        SecurityManager security = System.getSecurityManager();
451        try {
452            if (security != null) {
453                security.checkConnect(host, -1);
454            }
455        } catch (SecurityException e) {
456            return Inet4Address.LOOPBACK;
457        }
458        return lookupHostByName(host)[0];
459    }
460    private static native String gethostname();
461
462    /**
463     * Gets the hashcode of the represented IP address.
464     *
465     * @return the appropriate hashcode value.
466     */
467    @Override
468    public int hashCode() {
469        return Arrays.hashCode(ipaddress);
470    }
471
472    /*
473     * Returns whether this address is an IP multicast address or not. This
474     * implementation returns always {@code false}.
475     *
476     * @return {@code true} if this address is in the multicast group, {@code
477     *         false} otherwise.
478     */
479    public boolean isMulticastAddress() {
480        return false;
481    }
482
483    /**
484     * Resolves a hostname to its IP addresses using a cache.
485     *
486     * @param host the hostname to resolve.
487     * @return the IP addresses of the host.
488     */
489    private static InetAddress[] lookupHostByName(String host) throws UnknownHostException {
490        BlockGuard.getThreadPolicy().onNetwork();
491        // Do we have a result cached?
492        InetAddress[] cachedResult = addressCache.get(host);
493        if (cachedResult != null) {
494            if (cachedResult.length > 0) {
495                // A cached positive result.
496                return cachedResult;
497            } else {
498                // A cached negative result.
499                throw new UnknownHostException(host);
500            }
501        }
502        try {
503            InetAddress[] addresses = bytesToInetAddresses(getaddrinfo(host), host);
504            addressCache.put(host, addresses);
505            return addresses;
506        } catch (UnknownHostException e) {
507            addressCache.putUnknownHost(host);
508            throw new UnknownHostException(host);
509        }
510    }
511    private static native byte[][] getaddrinfo(String name) throws UnknownHostException;
512
513    /**
514     * Query the IP stack for the host address. The host is in address form.
515     *
516     * @param addr
517     *            the host address to lookup.
518     * @throws UnknownHostException
519     *             if an error occurs during lookup.
520     */
521    static InetAddress getHostByAddrImpl(byte[] addr)
522            throws UnknownHostException {
523        BlockGuard.getThreadPolicy().onNetwork();
524        if (addr.length == 4) {
525            return new Inet4Address(addr, getnameinfo(addr));
526        } else if (addr.length == 16) {
527            return new Inet6Address(addr, getnameinfo(addr));
528        } else {
529            throw new UnknownHostException(wrongAddressLength());
530        }
531    }
532
533    /**
534     * Resolves an IP address to a hostname. Thread safe.
535     */
536    private static native String getnameinfo(byte[] addr);
537
538    static String getHostNameInternal(String host, boolean isCheck) throws UnknownHostException {
539        if (host == null || 0 == host.length()) {
540            return Inet4Address.LOOPBACK.getHostAddress();
541        }
542        if (isHostName(host)) {
543            if (isCheck) {
544                SecurityManager sm = System.getSecurityManager();
545                if (sm != null) {
546                    sm.checkConnect(host, -1);
547                }
548            }
549            return lookupHostByName(host)[0].getHostAddress();
550        }
551        return host;
552    }
553
554    /**
555     * Returns a string containing a concise, human-readable description of this
556     * IP address.
557     *
558     * @return the description, as host/address.
559     */
560    @Override
561    public String toString() {
562        return (hostName == null ? "" : hostName) + "/" + getHostAddress();
563    }
564
565    /**
566     * Returns true if the string is a host name, false if it is an IP Address.
567     */
568    static boolean isHostName(String value) {
569        try {
570            ipStringToByteArray(value);
571            return false;
572        } catch (UnknownHostException e) {
573            return true;
574        }
575    }
576
577    /**
578     * Returns whether this address is a loopback address or not. This
579     * implementation returns always {@code false}. Valid IPv4 loopback
580     * addresses are 127.d.d.d The only valid IPv6 loopback address is ::1.
581     *
582     * @return {@code true} if this instance represents a loopback address,
583     *         {@code false} otherwise.
584     */
585    public boolean isLoopbackAddress() {
586        return false;
587    }
588
589    /**
590     * Returns whether this address is a link-local address or not. This
591     * implementation returns always {@code false}.
592     * <p>
593     * Valid IPv6 link-local addresses are FE80::0 through to
594     * FEBF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF.
595     * <p>
596     * There are no valid IPv4 link-local addresses.
597     *
598     * @return {@code true} if this instance represents a link-local address,
599     *         {@code false} otherwise.
600     */
601    public boolean isLinkLocalAddress() {
602        return false;
603    }
604
605    /**
606     * Returns whether this address is a site-local address or not. This
607     * implementation returns always {@code false}.
608     * <p>
609     * Valid IPv6 site-local addresses are FEC0::0 through to
610     * FEFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF.
611     * <p>
612     * There are no valid IPv4 site-local addresses.
613     *
614     * @return {@code true} if this instance represents a site-local address,
615     *         {@code false} otherwise.
616     */
617    public boolean isSiteLocalAddress() {
618        return false;
619    }
620
621    /**
622     * Returns whether this address is a global multicast address or not. This
623     * implementation returns always {@code false}.
624     * <p>
625     * Valid IPv6 link-global multicast addresses are FFxE:/112 where x is a set
626     * of flags, and the additional 112 bits make up the global multicast
627     * address space.
628     * <p>
629     * Valid IPv4 global multicast addresses are between: 224.0.1.0 to
630     * 238.255.255.255.
631     *
632     * @return {@code true} if this instance represents a global multicast
633     *         address, {@code false} otherwise.
634     */
635    public boolean isMCGlobal() {
636        return false;
637    }
638
639    /**
640     * Returns whether this address is a node-local multicast address or not.
641     * This implementation returns always {@code false}.
642     * <p>
643     * Valid IPv6 node-local multicast addresses are FFx1:/112 where x is a set
644     * of flags, and the additional 112 bits make up the node-local multicast
645     * address space.
646     * <p>
647     * There are no valid IPv4 node-local multicast addresses.
648     *
649     * @return {@code true} if this instance represents a node-local multicast
650     *         address, {@code false} otherwise.
651     */
652    public boolean isMCNodeLocal() {
653        return false;
654    }
655
656    /**
657     * Returns whether this address is a link-local multicast address or not.
658     * This implementation returns always {@code false}.
659     * <p>
660     * Valid IPv6 link-local multicast addresses are FFx2:/112 where x is a set
661     * of flags, and the additional 112 bits make up the link-local multicast
662     * address space.
663     * <p>
664     * Valid IPv4 link-local addresses are between: 224.0.0.0 to 224.0.0.255
665     *
666     * @return {@code true} if this instance represents a link-local multicast
667     *         address, {@code false} otherwise.
668     */
669    public boolean isMCLinkLocal() {
670        return false;
671    }
672
673    /**
674     * Returns whether this address is a site-local multicast address or not.
675     * This implementation returns always {@code false}.
676     * <p>
677     * Valid IPv6 site-local multicast addresses are FFx5:/112 where x is a set
678     * of flags, and the additional 112 bits make up the site-local multicast
679     * address space.
680     * <p>
681     * Valid IPv4 site-local addresses are between: 239.252.0.0 to
682     * 239.255.255.255
683     *
684     * @return {@code true} if this instance represents a site-local multicast
685     *         address, {@code false} otherwise.
686     */
687    public boolean isMCSiteLocal() {
688        return false;
689    }
690
691    /**
692     * Returns whether this address is a organization-local multicast address or
693     * not. This implementation returns always {@code false}.
694     * <p>
695     * Valid IPv6 organization-local multicast addresses are FFx8:/112 where x
696     * is a set of flags, and the additional 112 bits make up the
697     * organization-local multicast address space.
698     * <p>
699     * Valid IPv4 organization-local addresses are between: 239.192.0.0 to
700     * 239.251.255.255
701     *
702     * @return {@code true} if this instance represents a organization-local
703     *         multicast address, {@code false} otherwise.
704     */
705    public boolean isMCOrgLocal() {
706        return false;
707    }
708
709    /**
710     * Returns whether this is a wildcard address or not. This implementation
711     * returns always {@code false}.
712     *
713     * @return {@code true} if this instance represents a wildcard address,
714     *         {@code false} otherwise.
715     */
716    public boolean isAnyLocalAddress() {
717        return false;
718    }
719
720    /**
721     * Tries to reach this {@code InetAddress}. This method first tries to use
722     * ICMP <i>(ICMP ECHO REQUEST)</i>. When first step fails, a TCP connection
723     * on port 7 (Echo) of the remote host is established.
724     *
725     * @param timeout
726     *            timeout in milliseconds before the test fails if no connection
727     *            could be established.
728     * @return {@code true} if this address is reachable, {@code false}
729     *         otherwise.
730     * @throws IOException
731     *             if an error occurs during an I/O operation.
732     * @throws IllegalArgumentException
733     *             if timeout is less than zero.
734     */
735    public boolean isReachable(int timeout) throws IOException {
736        return isReachable(null, 0, timeout);
737    }
738
739    /**
740     * Tries to reach this {@code InetAddress}. This method first tries to use
741     * ICMP <i>(ICMP ECHO REQUEST)</i>. When first step fails, a TCP connection
742     * on port 7 (Echo) of the remote host is established.
743     *
744     * @param networkInterface
745     *            the network interface on which to connection should be
746     *            established.
747     * @param ttl
748     *            the maximum count of hops (time-to-live).
749     * @param timeout
750     *            timeout in milliseconds before the test fails if no connection
751     *            could be established.
752     * @return {@code true} if this address is reachable, {@code false}
753     *         otherwise.
754     * @throws IOException
755     *             if an error occurs during an I/O operation.
756     * @throws IllegalArgumentException
757     *             if ttl or timeout is less than zero.
758     */
759    public boolean isReachable(NetworkInterface networkInterface, final int ttl,
760            final int timeout) throws IOException {
761        if (ttl < 0 || timeout < 0) {
762            throw new IllegalArgumentException("ttl < 0 || timeout < 0");
763        }
764        if (networkInterface == null) {
765            return isReachableByTCP(this, null, timeout);
766        } else {
767            return isReachableByMultiThread(networkInterface, ttl, timeout);
768        }
769    }
770
771    /*
772     * Uses multi-Thread to try if isReachable, returns true if any of threads
773     * returns in time
774     */
775    private boolean isReachableByMultiThread(NetworkInterface netif,
776            final int ttl, final int timeout)
777            throws IOException {
778        List<InetAddress> addresses = Collections.list(netif.getInetAddresses());
779        if (addresses.isEmpty()) {
780            return false;
781        }
782        reached = false;
783        addrCount = addresses.size();
784        boolean needWait = false;
785        for (final InetAddress addr : addresses) {
786            // loopback interface can only reach to local addresses
787            if (addr.isLoopbackAddress()) {
788                Enumeration<NetworkInterface> NetworkInterfaces = NetworkInterface
789                        .getNetworkInterfaces();
790                while (NetworkInterfaces.hasMoreElements()) {
791                    NetworkInterface networkInterface = NetworkInterfaces
792                            .nextElement();
793                    Enumeration<InetAddress> localAddresses = networkInterface
794                            .getInetAddresses();
795                    while (localAddresses.hasMoreElements()) {
796                        if (InetAddress.this.equals(localAddresses
797                                .nextElement())) {
798                            return true;
799                        }
800                    }
801                }
802
803                synchronized (waitReachable) {
804                    addrCount--;
805
806                    if (addrCount == 0) {
807                        // if count equals zero, all thread
808                        // expired,notifies main thread
809                        waitReachable.notifyAll();
810                    }
811                }
812                continue;
813            }
814
815            needWait = true;
816            new Thread() {
817                @Override public void run() {
818                    /*
819                     * Spec violation! This implementation doesn't attempt an
820                     * ICMP; it skips right to TCP echo.
821                     */
822                    boolean threadReached = false;
823                    try {
824                        threadReached = isReachableByTCP(addr, InetAddress.this, timeout);
825                    } catch (IOException e) {
826                    }
827
828                    synchronized (waitReachable) {
829                        if (threadReached) {
830                            // if thread reached this address, sets reached to
831                            // true and notifies main thread
832                            reached = true;
833                            waitReachable.notifyAll();
834                        } else {
835                            addrCount--;
836                            if (0 == addrCount) {
837                                // if count equals zero, all thread
838                                // expired,notifies main thread
839                                waitReachable.notifyAll();
840                            }
841                        }
842                    }
843                }
844            }.start();
845        }
846
847        if (needWait) {
848            synchronized (waitReachable) {
849                try {
850                    while (!reached && (addrCount != 0)) {
851                        // wait for notification
852                        waitReachable.wait(1000);
853                    }
854                } catch (InterruptedException e) {
855                    // do nothing
856                }
857                return reached;
858            }
859        }
860
861        return false;
862    }
863
864    private boolean isReachableByTCP(InetAddress destination, InetAddress source, int timeout)
865            throws IOException {
866        FileDescriptor fd = new FileDescriptor();
867        boolean reached = false;
868        NETIMPL.createStreamSocket(fd);
869        try {
870            if (null != source) {
871                NETIMPL.bind(fd, source, 0);
872            }
873            NETIMPL.connect(fd, destination, 7, timeout);
874            reached = true;
875        } catch (IOException e) {
876            if (ERRMSG_CONNECTION_REFUSED.equals(e.getMessage())) {
877                // Connection refused means the IP is reachable
878                reached = true;
879            }
880        }
881
882        NETIMPL.close(fd);
883
884        return reached;
885    }
886
887    /**
888     * Returns the {@code InetAddress} corresponding to the array of bytes. In
889     * the case of an IPv4 address there must be exactly 4 bytes and for IPv6
890     * exactly 16 bytes. If not, an {@code UnknownHostException} is thrown.
891     * <p>
892     * The IP address is not validated by a name service.
893     * <p>
894     * The high order byte is {@code ipAddress[0]}.
895     *
896     * @param ipAddress
897     *            is either a 4 (IPv4) or 16 (IPv6) byte long array.
898     * @return an {@code InetAddress} instance representing the given IP address
899     *         {@code ipAddress}.
900     * @throws UnknownHostException
901     *             if the given byte array has no valid length.
902     */
903    public static InetAddress getByAddress(byte[] ipAddress)
904            throws UnknownHostException {
905        // simply call the method by the same name specifying the default scope
906        // id of 0
907        return getByAddressInternal(null, ipAddress, 0);
908    }
909
910    /**
911     * Returns the {@code InetAddress} corresponding to the array of bytes. In
912     * the case of an IPv4 address there must be exactly 4 bytes and for IPv6
913     * exactly 16 bytes. If not, an {@code UnknownHostException} is thrown. The
914     * IP address is not validated by a name service. The high order byte is
915     * {@code ipAddress[0]}.
916     *
917     * @param ipAddress
918     *            either a 4 (IPv4) or 16 (IPv6) byte array.
919     * @param scope_id
920     *            the scope id for an IPV6 scoped address. If not a scoped
921     *            address just pass in 0.
922     * @return the InetAddress
923     * @throws UnknownHostException
924     */
925    static InetAddress getByAddress(byte[] ipAddress, int scope_id)
926            throws UnknownHostException {
927        return getByAddressInternal(null, ipAddress, scope_id);
928    }
929
930    private static boolean isIPv4MappedAddress(byte ipAddress[]) {
931        // Check if the address matches ::FFFF:d.d.d.d
932        // The first 10 bytes are 0. The next to are -1 (FF).
933        // The last 4 bytes are varied.
934        if (ipAddress == null || ipAddress.length != 16) {
935            return false;
936        }
937        for (int i = 0; i < 10; i++) {
938            if (ipAddress[i] != 0) {
939                return false;
940            }
941        }
942        if (ipAddress[10] != -1 || ipAddress[11] != -1) {
943            return false;
944        }
945        return true;
946    }
947
948    private static byte[] ipv4MappedToIPv4(byte[] mappedAddress) {
949        byte[] ipv4Address = new byte[4];
950        for(int i = 0; i < 4; i++) {
951            ipv4Address[i] = mappedAddress[12 + i];
952        }
953        return ipv4Address;
954    }
955
956    /**
957     * Returns the {@code InetAddress} corresponding to the array of bytes, and
958     * the given hostname. In the case of an IPv4 address there must be exactly
959     * 4 bytes and for IPv6 exactly 16 bytes. If not, an {@code
960     * UnknownHostException} will be thrown.
961     * <p>
962     * The host name and IP address are not validated.
963     * <p>
964     * The hostname either be a machine alias or a valid IPv6 or IPv4 address
965     * format.
966     * <p>
967     * The high order byte is {@code ipAddress[0]}.
968     *
969     * @param hostName
970     *            the string representation of hostname or IP address.
971     * @param ipAddress
972     *            either a 4 (IPv4) or 16 (IPv6) byte long array.
973     * @return an {@code InetAddress} instance representing the given IP address
974     *         and hostname.
975     * @throws UnknownHostException
976     *             if the given byte array has no valid length.
977     */
978    public static InetAddress getByAddress(String hostName, byte[] ipAddress)
979            throws UnknownHostException {
980        // just call the method by the same name passing in a default scope id
981        // of 0
982        return getByAddressInternal(hostName, ipAddress, 0);
983    }
984
985    /**
986     * Returns the {@code InetAddress} corresponding to the array of bytes, and
987     * the given hostname. In the case of an IPv4 address there must be exactly
988     * 4 bytes and for IPv6 exactly 16 bytes. If not, an {@code
989     * UnknownHostException} is thrown. The host name and IP address are not
990     * validated. The hostname either be a machine alias or a valid IPv6 or IPv4
991     * address format. The high order byte is {@code ipAddress[0]}.
992     *
993     * @param hostName
994     *            string representation of hostname or IP address.
995     * @param ipAddress
996     *            either a 4 (IPv4) or 16 (IPv6) byte array.
997     * @param scope_id
998     *            the scope id for a scoped address. If not a scoped address
999     *            just pass in 0.
1000     * @return the InetAddress
1001     * @throws UnknownHostException
1002     */
1003    static InetAddress getByAddressInternal(String hostName, byte[] ipAddress,
1004            int scope_id) throws UnknownHostException {
1005        if (ipAddress == null) {
1006            throw new UnknownHostException("ipAddress == null");
1007        }
1008        switch (ipAddress.length) {
1009            case 4:
1010                return new Inet4Address(ipAddress.clone());
1011            case 16:
1012                // First check to see if the address is an IPv6-mapped
1013                // IPv4 address. If it is, then we can make it a IPv4
1014                // address, otherwise, we'll create an IPv6 address.
1015                if (isIPv4MappedAddress(ipAddress)) {
1016                    return new Inet4Address(ipv4MappedToIPv4(ipAddress));
1017                } else {
1018                    return new Inet6Address(ipAddress.clone(), scope_id);
1019                }
1020            default:
1021                throw new UnknownHostException(
1022                        "Invalid IP Address is neither 4 or 16 bytes: " + hostName);
1023        }
1024    }
1025
1026    /**
1027     * Takes the integer and chops it into 4 bytes, putting it into the byte
1028     * array starting with the high order byte at the index start. This method
1029     * makes no checks on the validity of the parameters.
1030     */
1031    static void intToBytes(int value, byte bytes[], int start) {
1032        // Shift the int so the current byte is right-most
1033        // Use a byte mask of 255 to single out the last byte.
1034        bytes[start] = (byte) ((value >> 24) & 255);
1035        bytes[start + 1] = (byte) ((value >> 16) & 255);
1036        bytes[start + 2] = (byte) ((value >> 8) & 255);
1037        bytes[start + 3] = (byte) (value & 255);
1038    }
1039
1040    /**
1041     * Takes the byte array and creates an integer out of four bytes starting at
1042     * start as the high-order byte. This method makes no checks on the validity
1043     * of the parameters.
1044     */
1045    static int bytesToInt(byte bytes[], int start) {
1046        // First mask the byte with 255, as when a negative
1047        // signed byte converts to an integer, it has bits
1048        // on in the first 3 bytes, we are only concerned
1049        // about the right-most 8 bits.
1050        // Then shift the rightmost byte to align with its
1051        // position in the integer.
1052        int value = ((bytes[start + 3] & 255))
1053                | ((bytes[start + 2] & 255) << 8)
1054                | ((bytes[start + 1] & 255) << 16)
1055                | ((bytes[start] & 255) << 24);
1056        return value;
1057    }
1058
1059    private static final ObjectStreamField[] serialPersistentFields = {
1060            new ObjectStreamField("address", Integer.TYPE),
1061            new ObjectStreamField("family", Integer.TYPE),
1062            new ObjectStreamField("hostName", String.class) };
1063
1064    private void writeObject(ObjectOutputStream stream) throws IOException {
1065        ObjectOutputStream.PutField fields = stream.putFields();
1066        if (ipaddress == null) {
1067            fields.put("address", 0);
1068        } else {
1069            fields.put("address", bytesToInt(ipaddress, 0));
1070        }
1071        fields.put("family", family);
1072        fields.put("hostName", hostName);
1073
1074        stream.writeFields();
1075    }
1076
1077    private void readObject(ObjectInputStream stream) throws IOException,
1078            ClassNotFoundException {
1079        ObjectInputStream.GetField fields = stream.readFields();
1080        int addr = fields.get("address", 0);
1081        ipaddress = new byte[4];
1082        intToBytes(addr, ipaddress, 0);
1083        hostName = (String) fields.get("hostName", null);
1084        family = fields.get("family", 2);
1085    }
1086
1087    /*
1088     * The spec requires that if we encounter a generic InetAddress in
1089     * serialized form then we should interpret it as an Inet4 address.
1090     */
1091    private Object readResolve() throws ObjectStreamException {
1092        return new Inet4Address(ipaddress, hostName);
1093    }
1094}
1095