InetAddress.java revision 3db0d1b07a79c3c871b0aa0929674adae3081b4f
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.getBoolean(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     * Query the IP stack for the host address. The host is in address form.
510     *
511     * @param addr
512     *            the host address to lookup.
513     * @throws UnknownHostException
514     *             if an error occurs during lookup.
515     */
516    static InetAddress getHostByAddrImpl(byte[] addr)
517            throws UnknownHostException {
518        BlockGuard.getThreadPolicy().onNetwork();
519        if (addr.length == 4) {
520            return new Inet4Address(addr, getnameinfo(addr));
521        } else if (addr.length == 16) {
522            return new Inet6Address(addr, getnameinfo(addr));
523        } else {
524            throw new UnknownHostException(wrongAddressLength());
525        }
526    }
527
528    /**
529     * Resolves an IP address to a hostname. Thread safe.
530     */
531    private static native String getnameinfo(byte[] addr);
532
533    static String getHostNameInternal(String host, boolean isCheck) throws UnknownHostException {
534        if (host == null || 0 == host.length()) {
535            return Inet4Address.LOOPBACK.getHostAddress();
536        }
537        if (isHostName(host)) {
538            if (isCheck) {
539                SecurityManager sm = System.getSecurityManager();
540                if (sm != null) {
541                    sm.checkConnect(host, -1);
542                }
543            }
544            return lookupHostByName(host)[0].getHostAddress();
545        }
546        return host;
547    }
548
549    /**
550     * Returns a string containing a concise, human-readable description of this
551     * IP address.
552     *
553     * @return the description, as host/address.
554     */
555    @Override
556    public String toString() {
557        return (hostName == null ? "" : hostName) + "/" + getHostAddress();
558    }
559
560    /**
561     * Returns true if the string is a host name, false if it is an IP Address.
562     */
563    static boolean isHostName(String value) {
564        try {
565            ipStringToByteArray(value);
566            return false;
567        } catch (UnknownHostException e) {
568            return true;
569        }
570    }
571
572    /**
573     * Returns whether this address is a loopback address or not. This
574     * implementation returns always {@code false}. Valid IPv4 loopback
575     * addresses are 127.d.d.d The only valid IPv6 loopback address is ::1.
576     *
577     * @return {@code true} if this instance represents a loopback address,
578     *         {@code false} otherwise.
579     */
580    public boolean isLoopbackAddress() {
581        return false;
582    }
583
584    /**
585     * Returns whether this address is a link-local address or not. This
586     * implementation returns always {@code false}.
587     * <p>
588     * Valid IPv6 link-local addresses are FE80::0 through to
589     * FEBF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF.
590     * <p>
591     * There are no valid IPv4 link-local addresses.
592     *
593     * @return {@code true} if this instance represents a link-local address,
594     *         {@code false} otherwise.
595     */
596    public boolean isLinkLocalAddress() {
597        return false;
598    }
599
600    /**
601     * Returns whether this address is a site-local address or not. This
602     * implementation returns always {@code false}.
603     * <p>
604     * Valid IPv6 site-local addresses are FEC0::0 through to
605     * FEFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF.
606     * <p>
607     * There are no valid IPv4 site-local addresses.
608     *
609     * @return {@code true} if this instance represents a site-local address,
610     *         {@code false} otherwise.
611     */
612    public boolean isSiteLocalAddress() {
613        return false;
614    }
615
616    /**
617     * Returns whether this address is a global multicast address or not. This
618     * implementation returns always {@code false}.
619     * <p>
620     * Valid IPv6 link-global multicast addresses are FFxE:/112 where x is a set
621     * of flags, and the additional 112 bits make up the global multicast
622     * address space.
623     * <p>
624     * Valid IPv4 global multicast addresses are between: 224.0.1.0 to
625     * 238.255.255.255.
626     *
627     * @return {@code true} if this instance represents a global multicast
628     *         address, {@code false} otherwise.
629     */
630    public boolean isMCGlobal() {
631        return false;
632    }
633
634    /**
635     * Returns whether this address is a node-local multicast address or not.
636     * This implementation returns always {@code false}.
637     * <p>
638     * Valid IPv6 node-local multicast addresses are FFx1:/112 where x is a set
639     * of flags, and the additional 112 bits make up the node-local multicast
640     * address space.
641     * <p>
642     * There are no valid IPv4 node-local multicast addresses.
643     *
644     * @return {@code true} if this instance represents a node-local multicast
645     *         address, {@code false} otherwise.
646     */
647    public boolean isMCNodeLocal() {
648        return false;
649    }
650
651    /**
652     * Returns whether this address is a link-local multicast address or not.
653     * This implementation returns always {@code false}.
654     * <p>
655     * Valid IPv6 link-local multicast addresses are FFx2:/112 where x is a set
656     * of flags, and the additional 112 bits make up the link-local multicast
657     * address space.
658     * <p>
659     * Valid IPv4 link-local addresses are between: 224.0.0.0 to 224.0.0.255
660     *
661     * @return {@code true} if this instance represents a link-local multicast
662     *         address, {@code false} otherwise.
663     */
664    public boolean isMCLinkLocal() {
665        return false;
666    }
667
668    /**
669     * Returns whether this address is a site-local multicast address or not.
670     * This implementation returns always {@code false}.
671     * <p>
672     * Valid IPv6 site-local multicast addresses are FFx5:/112 where x is a set
673     * of flags, and the additional 112 bits make up the site-local multicast
674     * address space.
675     * <p>
676     * Valid IPv4 site-local addresses are between: 239.252.0.0 to
677     * 239.255.255.255
678     *
679     * @return {@code true} if this instance represents a site-local multicast
680     *         address, {@code false} otherwise.
681     */
682    public boolean isMCSiteLocal() {
683        return false;
684    }
685
686    /**
687     * Returns whether this address is a organization-local multicast address or
688     * not. This implementation returns always {@code false}.
689     * <p>
690     * Valid IPv6 organization-local multicast addresses are FFx8:/112 where x
691     * is a set of flags, and the additional 112 bits make up the
692     * organization-local multicast address space.
693     * <p>
694     * Valid IPv4 organization-local addresses are between: 239.192.0.0 to
695     * 239.251.255.255
696     *
697     * @return {@code true} if this instance represents a organization-local
698     *         multicast address, {@code false} otherwise.
699     */
700    public boolean isMCOrgLocal() {
701        return false;
702    }
703
704    /**
705     * Returns whether this is a wildcard address or not. This implementation
706     * returns always {@code false}.
707     *
708     * @return {@code true} if this instance represents a wildcard address,
709     *         {@code false} otherwise.
710     */
711    public boolean isAnyLocalAddress() {
712        return false;
713    }
714
715    /**
716     * Tries to reach this {@code InetAddress}. This method first tries to use
717     * ICMP <i>(ICMP ECHO REQUEST)</i>. When first step fails, a TCP connection
718     * on port 7 (Echo) of the remote host is established.
719     *
720     * @param timeout
721     *            timeout in milliseconds before the test fails if no connection
722     *            could be established.
723     * @return {@code true} if this address is reachable, {@code false}
724     *         otherwise.
725     * @throws IOException
726     *             if an error occurs during an I/O operation.
727     * @throws IllegalArgumentException
728     *             if timeout is less than zero.
729     */
730    public boolean isReachable(int timeout) throws IOException {
731        return isReachable(null, 0, timeout);
732    }
733
734    /**
735     * Tries to reach this {@code InetAddress}. This method first tries to use
736     * ICMP <i>(ICMP ECHO REQUEST)</i>. When first step fails, a TCP connection
737     * on port 7 (Echo) of the remote host is established.
738     *
739     * @param networkInterface
740     *            the network interface on which to connection should be
741     *            established.
742     * @param ttl
743     *            the maximum count of hops (time-to-live).
744     * @param timeout
745     *            timeout in milliseconds before the test fails if no connection
746     *            could be established.
747     * @return {@code true} if this address is reachable, {@code false}
748     *         otherwise.
749     * @throws IOException
750     *             if an error occurs during an I/O operation.
751     * @throws IllegalArgumentException
752     *             if ttl or timeout is less than zero.
753     */
754    public boolean isReachable(NetworkInterface networkInterface, final int ttl,
755            final int timeout) throws IOException {
756        if (ttl < 0 || timeout < 0) {
757            throw new IllegalArgumentException("ttl < 0 || timeout < 0");
758        }
759        if (networkInterface == null) {
760            return isReachableByTCP(this, null, timeout);
761        } else {
762            return isReachableByMultiThread(networkInterface, ttl, timeout);
763        }
764    }
765
766    /*
767     * Uses multi-Thread to try if isReachable, returns true if any of threads
768     * returns in time
769     */
770    private boolean isReachableByMultiThread(NetworkInterface netif,
771            final int ttl, final int timeout)
772            throws IOException {
773        List<InetAddress> addresses = Collections.list(netif.getInetAddresses());
774        if (addresses.isEmpty()) {
775            return false;
776        }
777        reached = false;
778        addrCount = addresses.size();
779        boolean needWait = false;
780        for (final InetAddress addr : addresses) {
781            // loopback interface can only reach to local addresses
782            if (addr.isLoopbackAddress()) {
783                Enumeration<NetworkInterface> NetworkInterfaces = NetworkInterface
784                        .getNetworkInterfaces();
785                while (NetworkInterfaces.hasMoreElements()) {
786                    NetworkInterface networkInterface = NetworkInterfaces
787                            .nextElement();
788                    Enumeration<InetAddress> localAddresses = networkInterface
789                            .getInetAddresses();
790                    while (localAddresses.hasMoreElements()) {
791                        if (InetAddress.this.equals(localAddresses
792                                .nextElement())) {
793                            return true;
794                        }
795                    }
796                }
797
798                synchronized (waitReachable) {
799                    addrCount--;
800
801                    if (addrCount == 0) {
802                        // if count equals zero, all thread
803                        // expired,notifies main thread
804                        waitReachable.notifyAll();
805                    }
806                }
807                continue;
808            }
809
810            needWait = true;
811            new Thread() {
812                @Override public void run() {
813                    /*
814                     * Spec violation! This implementation doesn't attempt an
815                     * ICMP; it skips right to TCP echo.
816                     */
817                    boolean threadReached = false;
818                    try {
819                        threadReached = isReachableByTCP(addr, InetAddress.this, timeout);
820                    } catch (IOException e) {
821                    }
822
823                    synchronized (waitReachable) {
824                        if (threadReached) {
825                            // if thread reached this address, sets reached to
826                            // true and notifies main thread
827                            reached = true;
828                            waitReachable.notifyAll();
829                        } else {
830                            addrCount--;
831                            if (0 == addrCount) {
832                                // if count equals zero, all thread
833                                // expired,notifies main thread
834                                waitReachable.notifyAll();
835                            }
836                        }
837                    }
838                }
839            }.start();
840        }
841
842        if (needWait) {
843            synchronized (waitReachable) {
844                try {
845                    while (!reached && (addrCount != 0)) {
846                        // wait for notification
847                        waitReachable.wait(1000);
848                    }
849                } catch (InterruptedException e) {
850                    // do nothing
851                }
852                return reached;
853            }
854        }
855
856        return false;
857    }
858
859    private boolean isReachableByTCP(InetAddress destination, InetAddress source, int timeout)
860            throws IOException {
861        FileDescriptor fd = new FileDescriptor();
862        boolean reached = false;
863        Platform.NETWORK.socket(fd, true);
864        try {
865            if (null != source) {
866                Platform.NETWORK.bind(fd, source, 0);
867            }
868            Platform.NETWORK.connect(fd, destination, 7, timeout);
869            reached = true;
870        } catch (IOException e) {
871            if (ERRMSG_CONNECTION_REFUSED.equals(e.getMessage())) {
872                // Connection refused means the IP is reachable
873                reached = true;
874            }
875        }
876
877        Platform.NETWORK.close(fd);
878
879        return reached;
880    }
881
882    /**
883     * Returns the {@code InetAddress} corresponding to the array of bytes. In
884     * the case of an IPv4 address there must be exactly 4 bytes and for IPv6
885     * exactly 16 bytes. If not, an {@code UnknownHostException} is thrown.
886     * <p>
887     * The IP address is not validated by a name service.
888     * <p>
889     * The high order byte is {@code ipAddress[0]}.
890     *
891     * @param ipAddress
892     *            is either a 4 (IPv4) or 16 (IPv6) byte long array.
893     * @return an {@code InetAddress} instance representing the given IP address
894     *         {@code ipAddress}.
895     * @throws UnknownHostException
896     *             if the given byte array has no valid length.
897     */
898    public static InetAddress getByAddress(byte[] ipAddress)
899            throws UnknownHostException {
900        // simply call the method by the same name specifying the default scope
901        // id of 0
902        return getByAddressInternal(null, ipAddress, 0);
903    }
904
905    /**
906     * Returns the {@code InetAddress} corresponding to the array of bytes. In
907     * the case of an IPv4 address there must be exactly 4 bytes and for IPv6
908     * exactly 16 bytes. If not, an {@code UnknownHostException} is thrown. The
909     * IP address is not validated by a name service. The high order byte is
910     * {@code ipAddress[0]}.
911     *
912     * @param ipAddress
913     *            either a 4 (IPv4) or 16 (IPv6) byte array.
914     * @param scope_id
915     *            the scope id for an IPV6 scoped address. If not a scoped
916     *            address just pass in 0.
917     * @return the InetAddress
918     * @throws UnknownHostException
919     */
920    static InetAddress getByAddress(byte[] ipAddress, int scope_id)
921            throws UnknownHostException {
922        return getByAddressInternal(null, ipAddress, scope_id);
923    }
924
925    private static boolean isIPv4MappedAddress(byte ipAddress[]) {
926        // Check if the address matches ::FFFF:d.d.d.d
927        // The first 10 bytes are 0. The next to are -1 (FF).
928        // The last 4 bytes are varied.
929        if (ipAddress == null || ipAddress.length != 16) {
930            return false;
931        }
932        for (int i = 0; i < 10; i++) {
933            if (ipAddress[i] != 0) {
934                return false;
935            }
936        }
937        if (ipAddress[10] != -1 || ipAddress[11] != -1) {
938            return false;
939        }
940        return true;
941    }
942
943    private static byte[] ipv4MappedToIPv4(byte[] mappedAddress) {
944        byte[] ipv4Address = new byte[4];
945        for(int i = 0; i < 4; i++) {
946            ipv4Address[i] = mappedAddress[12 + i];
947        }
948        return ipv4Address;
949    }
950
951    /**
952     * Returns the {@code InetAddress} corresponding to the array of bytes, and
953     * the given hostname. In the case of an IPv4 address there must be exactly
954     * 4 bytes and for IPv6 exactly 16 bytes. If not, an {@code
955     * UnknownHostException} will be thrown.
956     * <p>
957     * The host name and IP address are not validated.
958     * <p>
959     * The hostname either be a machine alias or a valid IPv6 or IPv4 address
960     * format.
961     * <p>
962     * The high order byte is {@code ipAddress[0]}.
963     *
964     * @param hostName
965     *            the string representation of hostname or IP address.
966     * @param ipAddress
967     *            either a 4 (IPv4) or 16 (IPv6) byte long array.
968     * @return an {@code InetAddress} instance representing the given IP address
969     *         and hostname.
970     * @throws UnknownHostException
971     *             if the given byte array has no valid length.
972     */
973    public static InetAddress getByAddress(String hostName, byte[] ipAddress)
974            throws UnknownHostException {
975        // just call the method by the same name passing in a default scope id
976        // of 0
977        return getByAddressInternal(hostName, ipAddress, 0);
978    }
979
980    /**
981     * Returns the {@code InetAddress} corresponding to the array of bytes, and
982     * the given hostname. In the case of an IPv4 address there must be exactly
983     * 4 bytes and for IPv6 exactly 16 bytes. If not, an {@code
984     * UnknownHostException} is thrown. The host name and IP address are not
985     * validated. The hostname either be a machine alias or a valid IPv6 or IPv4
986     * address format. The high order byte is {@code ipAddress[0]}.
987     *
988     * @param hostName
989     *            string representation of hostname or IP address.
990     * @param ipAddress
991     *            either a 4 (IPv4) or 16 (IPv6) byte array.
992     * @param scope_id
993     *            the scope id for a scoped address. If not a scoped address
994     *            just pass in 0.
995     * @return the InetAddress
996     * @throws UnknownHostException
997     */
998    static InetAddress getByAddressInternal(String hostName, byte[] ipAddress,
999            int scope_id) throws UnknownHostException {
1000        if (ipAddress == null) {
1001            throw new UnknownHostException("ipAddress == null");
1002        }
1003        switch (ipAddress.length) {
1004            case 4:
1005                return new Inet4Address(ipAddress.clone());
1006            case 16:
1007                // First check to see if the address is an IPv6-mapped
1008                // IPv4 address. If it is, then we can make it a IPv4
1009                // address, otherwise, we'll create an IPv6 address.
1010                if (isIPv4MappedAddress(ipAddress)) {
1011                    return new Inet4Address(ipv4MappedToIPv4(ipAddress));
1012                } else {
1013                    return new Inet6Address(ipAddress.clone(), scope_id);
1014                }
1015            default:
1016                throw new UnknownHostException(
1017                        "Invalid IP Address is neither 4 or 16 bytes: " + hostName);
1018        }
1019    }
1020
1021    /**
1022     * Takes the integer and chops it into 4 bytes, putting it into the byte
1023     * array starting with the high order byte at the index start. This method
1024     * makes no checks on the validity of the parameters.
1025     */
1026    static void intToBytes(int value, byte bytes[], int start) {
1027        // Shift the int so the current byte is right-most
1028        // Use a byte mask of 255 to single out the last byte.
1029        bytes[start] = (byte) ((value >> 24) & 255);
1030        bytes[start + 1] = (byte) ((value >> 16) & 255);
1031        bytes[start + 2] = (byte) ((value >> 8) & 255);
1032        bytes[start + 3] = (byte) (value & 255);
1033    }
1034
1035    /**
1036     * Takes the byte array and creates an integer out of four bytes starting at
1037     * start as the high-order byte. This method makes no checks on the validity
1038     * of the parameters.
1039     */
1040    static int bytesToInt(byte bytes[], int start) {
1041        // First mask the byte with 255, as when a negative
1042        // signed byte converts to an integer, it has bits
1043        // on in the first 3 bytes, we are only concerned
1044        // about the right-most 8 bits.
1045        // Then shift the rightmost byte to align with its
1046        // position in the integer.
1047        int value = ((bytes[start + 3] & 255))
1048                | ((bytes[start + 2] & 255) << 8)
1049                | ((bytes[start + 1] & 255) << 16)
1050                | ((bytes[start] & 255) << 24);
1051        return value;
1052    }
1053
1054    private static final ObjectStreamField[] serialPersistentFields = {
1055            new ObjectStreamField("address", Integer.TYPE),
1056            new ObjectStreamField("family", Integer.TYPE),
1057            new ObjectStreamField("hostName", String.class) };
1058
1059    private void writeObject(ObjectOutputStream stream) throws IOException {
1060        ObjectOutputStream.PutField fields = stream.putFields();
1061        if (ipaddress == null) {
1062            fields.put("address", 0);
1063        } else {
1064            fields.put("address", bytesToInt(ipaddress, 0));
1065        }
1066        fields.put("family", family);
1067        fields.put("hostName", hostName);
1068
1069        stream.writeFields();
1070    }
1071
1072    private void readObject(ObjectInputStream stream) throws IOException,
1073            ClassNotFoundException {
1074        ObjectInputStream.GetField fields = stream.readFields();
1075        int addr = fields.get("address", 0);
1076        ipaddress = new byte[4];
1077        intToBytes(addr, ipaddress, 0);
1078        hostName = (String) fields.get("hostName", null);
1079        family = fields.get("family", 2);
1080    }
1081
1082    /*
1083     * The spec requires that if we encounter a generic InetAddress in
1084     * serialized form then we should interpret it as an Inet4 address.
1085     */
1086    private Object readResolve() throws ObjectStreamException {
1087        return new Inet4Address(ipaddress, hostName);
1088    }
1089}
1090