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