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