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