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 android.system.ErrnoException;
21import android.system.GaiException;
22import android.system.StructAddrinfo;
23import dalvik.system.BlockGuard;
24import java.io.FileDescriptor;
25import java.io.IOException;
26import java.io.ObjectInputStream;
27import java.io.ObjectOutputStream;
28import java.io.ObjectStreamException;
29import java.io.ObjectStreamField;
30import java.io.Serializable;
31import java.nio.ByteOrder;
32import java.util.Arrays;
33import java.util.Collections;
34import java.util.concurrent.atomic.AtomicBoolean;
35import java.util.concurrent.CountDownLatch;
36import java.util.List;
37import libcore.io.IoBridge;
38import libcore.io.Libcore;
39import libcore.io.Memory;
40import static android.system.OsConstants.*;
41
42/**
43 * An Internet Protocol (IP) address. This can be either an IPv4 address or an IPv6 address, and
44 * in practice you'll have an instance of either {@code Inet4Address} or {@code Inet6Address} (this
45 * class cannot be instantiated directly). Most code does not need to distinguish between the two
46 * families, and should use {@code InetAddress}.
47 *
48 * <p>An {@code InetAddress} may have a hostname (accessible via {@code getHostName}), but may not,
49 * depending on how the {@code InetAddress} was created.
50 *
51 * <h4>IPv4 numeric address formats</h4>
52 * <p>The {@code getAllByName} method accepts IPv4 addresses in the "decimal-dotted-quad" form only:
53 * <ul>
54 * <li>{@code "1.2.3.4"} - 1.2.3.4
55 * </ul>
56 *
57 * <h4>IPv6 numeric address formats</h4>
58 * <p>The {@code getAllByName} method accepts IPv6 addresses in the following forms (this text
59 * comes from <a href="http://www.ietf.org/rfc/rfc2373.txt">RFC 2373</a>, which you should consult
60 * for full details of IPv6 addressing):
61 * <ul>
62 * <li><p>The preferred form is {@code x:x:x:x:x:x:x:x}, where the 'x's are the
63 * hexadecimal values of the eight 16-bit pieces of the address.
64 * Note that it is not necessary to write the leading zeros in an
65 * individual field, but there must be at least one numeral in every
66 * field (except for the case described in the next bullet).
67 * Examples:
68 * <pre>
69 *     FEDC:BA98:7654:3210:FEDC:BA98:7654:3210
70 *     1080:0:0:0:8:800:200C:417A</pre>
71 * </li>
72 * <li>Due to some methods of allocating certain styles of IPv6
73 * addresses, it will be common for addresses to contain long strings
74 * of zero bits.  In order to make writing addresses containing zero
75 * bits easier a special syntax is available to compress the zeros.
76 * The use of "::" indicates multiple groups of 16-bits of zeros.
77 * The "::" can only appear once in an address.  The "::" can also be
78 * used to compress the leading and/or trailing zeros in an address.
79 *
80 * For example the following addresses:
81 * <pre>
82 *     1080:0:0:0:8:800:200C:417A  a unicast address
83 *     FF01:0:0:0:0:0:0:101        a multicast address
84 *     0:0:0:0:0:0:0:1             the loopback address
85 *     0:0:0:0:0:0:0:0             the unspecified addresses</pre>
86 * may be represented as:
87 * <pre>
88 *     1080::8:800:200C:417A       a unicast address
89 *     FF01::101                   a multicast address
90 *     ::1                         the loopback address
91 *     ::                          the unspecified addresses</pre>
92 * </li>
93 * <li><p>An alternative form that is sometimes more convenient when dealing
94 * with a mixed environment of IPv4 and IPv6 nodes is
95 * {@code x:x:x:x:x:x:d.d.d.d}, where the 'x's are the hexadecimal values of
96 * the six high-order 16-bit pieces of the address, and the 'd's are
97 * the decimal values of the four low-order 8-bit pieces of the
98 * address (standard IPv4 representation).  Examples:
99 * <pre>
100 *     0:0:0:0:0:0:13.1.68.3
101 *     0:0:0:0:0:FFFF:129.144.52.38</pre>
102 * or in compressed form:
103 * <pre>
104 *     ::13.1.68.3
105 *     ::FFFF:129.144.52.38</pre>
106 * </li>
107 * </ul>
108 * <p>Scopes are given using a trailing {@code %} followed by the scope id, as in
109 * {@code 1080::8:800:200C:417A%2} or {@code 1080::8:800:200C:417A%en0}.
110 * See <a href="https://www.ietf.org/rfc/rfc4007.txt">RFC 4007</a> for more on IPv6's scoped
111 * address architecture.
112 *
113 * <p>Additionally, for backwards compatibility, IPv6 addresses may be surrounded by square
114 * brackets.
115 *
116 * <h4>DNS caching</h4>
117 * <p>In Android 4.0 (Ice Cream Sandwich) and earlier, DNS caching was performed both by
118 * InetAddress and by the C library, which meant that DNS TTLs could not be honored correctly.
119 * In later releases, caching is done solely by the C library and DNS TTLs are honored.
120 *
121 * @see Inet4Address
122 * @see Inet6Address
123 */
124public class InetAddress implements Serializable {
125    /** Our Java-side DNS cache. */
126    private static final AddressCache addressCache = new AddressCache();
127
128    private static final long serialVersionUID = 3286316764910316507L;
129
130    /** Using NetID of NETID_UNSET indicates resolution should be done on default network. */
131    private static final int NETID_UNSET = 0;
132
133    private int family;
134
135    byte[] ipaddress;
136
137    String hostName;
138
139    /**
140     * Used by the DatagramSocket.disconnect implementation.
141     * @hide internal use only
142     */
143    public static final InetAddress UNSPECIFIED = new InetAddress(AF_UNSPEC, null, null);
144
145    /**
146     * Constructs an {@code InetAddress}.
147     *
148     * Note: this constructor is for subclasses only.
149     */
150    InetAddress(int family, byte[] ipaddress, String hostName) {
151        this.family = family;
152        this.ipaddress = ipaddress;
153        this.hostName = hostName;
154    }
155
156    /**
157     * Compares this {@code InetAddress} instance against the specified address
158     * in {@code obj}. Two addresses are equal if their address byte arrays have
159     * the same length and if the bytes in the arrays are equal.
160     *
161     * @param obj
162     *            the object to be tested for equality.
163     * @return {@code true} if both objects are equal, {@code false} otherwise.
164     */
165    @Override
166    public boolean equals(Object obj) {
167        if (!(obj instanceof InetAddress)) {
168            return false;
169        }
170        return Arrays.equals(this.ipaddress, ((InetAddress) obj).ipaddress);
171    }
172
173    /**
174     * Returns the IP address represented by this {@code InetAddress} instance
175     * as a byte array. The elements are in network order (the highest order
176     * address byte is in the zeroth element).
177     *
178     * @return the address in form of a byte array.
179     */
180    public byte[] getAddress() {
181        return ipaddress.clone();
182    }
183
184    /**
185     * Converts an array of byte arrays representing raw IP addresses of a host
186     * to an array of InetAddress objects.
187     *
188     * @param rawAddresses the raw addresses to convert.
189     * @param hostName the hostname corresponding to the IP address.
190     * @return the corresponding InetAddresses, appropriately sorted.
191     */
192    private static InetAddress[] bytesToInetAddresses(byte[][] rawAddresses, String hostName)
193            throws UnknownHostException {
194        // Convert the byte arrays to InetAddresses.
195        InetAddress[] returnedAddresses = new InetAddress[rawAddresses.length];
196        for (int i = 0; i < rawAddresses.length; i++) {
197            returnedAddresses[i] = makeInetAddress(rawAddresses[i], hostName);
198        }
199        return returnedAddresses;
200    }
201
202    /**
203     * Gets all IP addresses associated with the given {@code host} identified
204     * by name or literal IP address. The IP address is resolved by the
205     * configured name service. If the host name is empty or {@code null} the
206     * IP addresses of the loopback interfaces are returned. If the host name
207     * is a literal IP address string an array with the corresponding single
208     * {@code InetAddress} is returned.
209     *
210     * @param host the hostname or literal IP string to be resolved.
211     * @return the array of addresses associated with the specified host.
212     * @throws UnknownHostException if the address lookup fails.
213     */
214    public static InetAddress[] getAllByName(String host) throws UnknownHostException {
215        return getAllByNameImpl(host, NETID_UNSET).clone();
216    }
217
218    /**
219     * Operates identically to {@code getAllByName} except host resolution is
220     * performed on the network designated by {@code netId}.
221     *
222     * @param host the hostname or literal IP string to be resolved.
223     * @param netId the network to use for host resolution.
224     * @return the array of addresses associated with the specified host.
225     * @throws UnknownHostException if the address lookup fails.
226     * @hide internal use only
227     */
228    public static InetAddress[] getAllByNameOnNet(String host, int netId) throws UnknownHostException {
229        return getAllByNameImpl(host, netId).clone();
230    }
231
232    /**
233     * Returns the InetAddresses for {@code host} on network {@code netId}. The
234     * returned array is shared and must be cloned before it is returned to
235     * application code.
236     */
237    private static InetAddress[] getAllByNameImpl(String host, int netId) throws UnknownHostException {
238        if (host == null || host.isEmpty()) {
239            return loopbackAddresses();
240        }
241
242        // Is it a numeric address?
243        InetAddress result = parseNumericAddressNoThrow(host);
244        if (result != null) {
245            result = disallowDeprecatedFormats(host, result);
246            if (result == null) {
247                throw new UnknownHostException("Deprecated IPv4 address format: " + host);
248            }
249            return new InetAddress[] { result };
250        }
251
252        return lookupHostByName(host, netId).clone();
253    }
254
255    private static InetAddress makeInetAddress(byte[] bytes, String hostName) throws UnknownHostException {
256        if (bytes.length == 4) {
257            return new Inet4Address(bytes, hostName);
258        } else if (bytes.length == 16) {
259            return new Inet6Address(bytes, hostName, 0);
260        } else {
261            throw badAddressLength(bytes);
262        }
263    }
264
265    private static InetAddress disallowDeprecatedFormats(String address, InetAddress inetAddress) {
266        // Only IPv4 addresses are problematic.
267        if (!(inetAddress instanceof Inet4Address) || address.indexOf(':') != -1) {
268            return inetAddress;
269        }
270        // If inet_pton(3) can't parse it, it must have been a deprecated format.
271        // We need to return inet_pton(3)'s result to ensure that numbers assumed to be octal
272        // by getaddrinfo(3) are reinterpreted by inet_pton(3) as decimal.
273        return Libcore.os.inet_pton(AF_INET, address);
274    }
275
276    private static InetAddress parseNumericAddressNoThrow(String address) {
277        // Accept IPv6 addresses (only) in square brackets for compatibility.
278        if (address.startsWith("[") && address.endsWith("]") && address.indexOf(':') != -1) {
279            address = address.substring(1, address.length() - 1);
280        }
281        StructAddrinfo hints = new StructAddrinfo();
282        hints.ai_flags = AI_NUMERICHOST;
283        InetAddress[] addresses = null;
284        try {
285            addresses = Libcore.os.android_getaddrinfo(address, hints, NETID_UNSET);
286        } catch (GaiException ignored) {
287        }
288        return (addresses != null) ? addresses[0] : null;
289    }
290
291    /**
292     * Returns the address of a host according to the given host string name
293     * {@code host}. The host string may be either a machine name or a dotted
294     * string IP address. If the latter, the {@code hostName} field is
295     * determined upon demand. {@code host} can be {@code null} which means that
296     * an address of the loopback interface is returned.
297     *
298     * @param host
299     *            the hostName to be resolved to an address or {@code null}.
300     * @return the {@code InetAddress} instance representing the host.
301     * @throws UnknownHostException
302     *             if the address lookup fails.
303     */
304    public static InetAddress getByName(String host) throws UnknownHostException {
305        return getAllByNameImpl(host, NETID_UNSET)[0];
306    }
307
308    /**
309     * Operates identically to {@code getByName} except host resolution is
310     * performed on the network designated by {@code netId}.
311     *
312     * @param host
313     *            the hostName to be resolved to an address or {@code null}.
314     * @param netId the network to use for host resolution.
315     * @return the {@code InetAddress} instance representing the host.
316     * @throws UnknownHostException if the address lookup fails.
317     * @hide internal use only
318     */
319    public static InetAddress getByNameOnNet(String host, int netId) throws UnknownHostException {
320        return getAllByNameImpl(host, netId)[0];
321    }
322
323    /**
324     * Returns the numeric representation of this IP address (such as "127.0.0.1").
325     */
326    public String getHostAddress() {
327        return Libcore.os.getnameinfo(this, NI_NUMERICHOST); // Can't throw.
328    }
329
330    /**
331     * Returns the host name corresponding to this IP address. This may or may not be a
332     * fully-qualified name. If the IP address could not be resolved, the numeric representation
333     * is returned instead (see {@link #getHostAddress}).
334     */
335    public String getHostName() {
336        if (hostName == null) {
337            try {
338                hostName = getHostByAddrImpl(this).hostName;
339            } catch (UnknownHostException ex) {
340                hostName = getHostAddress();
341            }
342        }
343        return hostName;
344    }
345
346    /**
347     * Returns the hostname if known, or the result of {@code #getHostAddress}.
348     * Unlike {@link #getHostName}, this method will never cause a DNS lookup.
349     *
350     * @hide For libcore situations that must avoid DNS lookups.
351     */
352    public String getHostString() {
353        if (hostName == null) {
354            return getHostAddress();
355        }
356        return hostName;
357    }
358
359    /**
360     * Returns the fully qualified hostname corresponding to this IP address.
361     */
362    public String getCanonicalHostName() {
363        try {
364            return getHostByAddrImpl(this).hostName;
365        } catch (UnknownHostException ex) {
366            return getHostAddress();
367        }
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;
409        return lookupHostByName(host, NETID_UNSET)[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     * Resolves a hostname to its IP addresses using a cache.
424     *
425     * @param host the hostname to resolve.
426     * @param netId the network to perform resolution upon.
427     * @return the IP addresses of the host.
428     */
429    private static InetAddress[] lookupHostByName(String host, int netId)
430            throws UnknownHostException {
431        BlockGuard.getThreadPolicy().onNetwork();
432        // Do we have a result cached?
433        Object cachedResult = addressCache.get(host, netId);
434        if (cachedResult != null) {
435            if (cachedResult instanceof InetAddress[]) {
436                // A cached positive result.
437                return (InetAddress[]) cachedResult;
438            } else {
439                // A cached negative result.
440                throw new UnknownHostException((String) cachedResult);
441            }
442        }
443        try {
444            StructAddrinfo hints = new StructAddrinfo();
445            hints.ai_flags = AI_ADDRCONFIG;
446            hints.ai_family = AF_UNSPEC;
447            // If we don't specify a socket type, every address will appear twice, once
448            // for SOCK_STREAM and one for SOCK_DGRAM. Since we do not return the family
449            // anyway, just pick one.
450            hints.ai_socktype = SOCK_STREAM;
451            InetAddress[] addresses = Libcore.os.android_getaddrinfo(host, hints, netId);
452            // TODO: should getaddrinfo set the hostname of the InetAddresses it returns?
453            for (InetAddress address : addresses) {
454                address.hostName = host;
455            }
456            addressCache.put(host, netId, addresses);
457            return addresses;
458        } catch (GaiException gaiException) {
459            // If the failure appears to have been a lack of INTERNET permission, throw a clear
460            // SecurityException to aid in debugging this common mistake.
461            // http://code.google.com/p/android/issues/detail?id=15722
462            if (gaiException.getCause() instanceof ErrnoException) {
463                if (((ErrnoException) gaiException.getCause()).errno == EACCES) {
464                    throw new SecurityException("Permission denied (missing INTERNET permission?)", gaiException);
465                }
466            }
467            // Otherwise, throw an UnknownHostException.
468            String detailMessage = "Unable to resolve host \"" + host + "\": " + Libcore.os.gai_strerror(gaiException.error);
469            addressCache.putUnknownHost(host, netId, detailMessage);
470            throw gaiException.rethrowAsUnknownHostException(detailMessage);
471        }
472    }
473
474    /**
475     * Removes all entries from the VM's DNS cache. This does not affect the C library's DNS
476     * cache, nor any caching DNS servers between you and the canonical server.
477     * @hide
478     */
479    public static void clearDnsCache() {
480        addressCache.clear();
481    }
482
483    private static InetAddress getHostByAddrImpl(InetAddress address) throws UnknownHostException {
484        BlockGuard.getThreadPolicy().onNetwork();
485        try {
486            String hostname = Libcore.os.getnameinfo(address, NI_NAMEREQD);
487            return makeInetAddress(address.ipaddress.clone(), hostname);
488        } catch (GaiException gaiException) {
489            throw gaiException.rethrowAsUnknownHostException();
490        }
491    }
492
493    /**
494     * Returns a string containing the host name (if available) and host address.
495     * For example: {@code "www.google.com/74.125.224.115"} or {@code "/127.0.0.1"}.
496     *
497     * <p>IPv6 addresses may additionally include an interface name or scope id.
498     * For example: {@code "www.google.com/2001:4860:4001:803::1013%eth0"} or
499     * {@code "/2001:4860:4001:803::1013%2"}.
500     */
501    @Override public String toString() {
502        return (hostName == null ? "" : hostName) + "/" + getHostAddress();
503    }
504
505    /**
506     * Returns true if the string is a valid numeric IPv4 or IPv6 address (such as "192.168.0.1").
507     * This copes with all forms of address that Java supports, detailed in the {@link InetAddress}
508     * class documentation.
509     *
510     * @hide used by frameworks/base to ensure that a getAllByName won't cause a DNS lookup.
511     */
512    public static boolean isNumeric(String address) {
513        InetAddress inetAddress = parseNumericAddressNoThrow(address);
514        return inetAddress != null && disallowDeprecatedFormats(address, inetAddress) != null;
515    }
516
517    /**
518     * Returns an InetAddress corresponding to the given numeric address (such
519     * as {@code "192.168.0.1"} or {@code "2001:4860:800d::68"}).
520     * This method will never do a DNS lookup. Non-numeric addresses are errors.
521     *
522     * @hide used by frameworks/base's NetworkUtils.numericToInetAddress
523     * @throws IllegalArgumentException if {@code numericAddress} is not a numeric address
524     */
525    public static InetAddress parseNumericAddress(String numericAddress) {
526        if (numericAddress == null || numericAddress.isEmpty()) {
527            return Inet6Address.LOOPBACK;
528        }
529        InetAddress result = parseNumericAddressNoThrow(numericAddress);
530        result = disallowDeprecatedFormats(numericAddress, result);
531        if (result == null) {
532            throw new IllegalArgumentException("Not a numeric address: " + numericAddress);
533        }
534        return result;
535    }
536
537    private static InetAddress[] loopbackAddresses() {
538        return new InetAddress[] { Inet6Address.LOOPBACK, Inet4Address.LOOPBACK };
539    }
540
541    /**
542     * Returns the IPv6 loopback address {@code ::1} or the IPv4 loopback address {@code 127.0.0.1}.
543     * @since 1.7
544     */
545    public static InetAddress getLoopbackAddress() {
546        return Inet6Address.LOOPBACK;
547    }
548
549    /**
550     * Returns whether this is the IPv6 unspecified wildcard address {@code ::}
551     * or the IPv4 "any" address, {@code 0.0.0.0}.
552     */
553    public boolean isAnyLocalAddress() {
554        return false;
555    }
556
557    /**
558     * Returns whether this address is a link-local address or not.
559     *
560     * <p>Valid IPv6 link-local addresses have the prefix {@code fe80::/10}.
561     *
562     * <p><a href="http://www.ietf.org/rfc/rfc3484.txt">RFC 3484</a>
563     * "Default Address Selection for Internet Protocol Version 6 (IPv6)" states
564     * that both IPv4 auto-configuration addresses (prefix {@code 169.254/16}) and
565     * IPv4 loopback addresses (prefix {@code 127/8}) have link-local scope, but
566     * {@link Inet4Address} only considers the auto-configuration addresses
567     * to have link-local scope. That is: the IPv4 loopback address returns false.
568     */
569    public boolean isLinkLocalAddress() {
570        return false;
571    }
572
573    /**
574     * Returns whether this address is a loopback address or not.
575     *
576     * <p>Valid IPv4 loopback addresses have the prefix {@code 127/8}.
577     *
578     * <p>The only valid IPv6 loopback address is {@code ::1}.
579     */
580    public boolean isLoopbackAddress() {
581        return false;
582    }
583
584    /**
585     * Returns whether this address is a global multicast address or not.
586     *
587     * <p>Valid IPv6 global multicast addresses have the prefix {@code ffxe::/16},
588     * where {@code x} is a set of flags and the additional 112 bits make
589     * up the global multicast address space.
590     *
591     * <p>Valid IPv4 global multicast addresses are the range of addresses
592     * from {@code 224.0.1.0} to {@code 238.255.255.255}.
593     */
594    public boolean isMCGlobal() {
595        return false;
596    }
597
598    /**
599     * Returns whether this address is a link-local multicast address or not.
600     *
601     * <p>Valid IPv6 link-local multicast addresses have the prefix {@code ffx2::/16},
602     * where x is a set of flags and the additional 112 bits make up the link-local multicast
603     * address space.
604     *
605     * <p>Valid IPv4 link-local multicast addresses have the prefix {@code 224.0.0/24}.
606     */
607    public boolean isMCLinkLocal() {
608        return false;
609    }
610
611    /**
612     * Returns whether this address is a node-local multicast address or not.
613     *
614     * <p>Valid IPv6 node-local multicast addresses have the prefix {@code ffx1::/16},
615     * where x is a set of flags and the additional 112 bits make up the link-local multicast
616     * address space.
617     *
618     * <p>There are no valid IPv4 node-local multicast addresses.
619     */
620    public boolean isMCNodeLocal() {
621        return false;
622    }
623
624    /**
625     * Returns whether this address is a organization-local multicast address or not.
626     *
627     * <p>Valid IPv6 organization-local multicast addresses have the prefix {@code ffx8::/16},
628     * where x is a set of flags and the additional 112 bits make up the link-local multicast
629     * address space.
630     *
631     * <p>Valid IPv4 organization-local multicast addresses have the prefix {@code 239.192/14}.
632     */
633    public boolean isMCOrgLocal() {
634        return false;
635    }
636
637    /**
638     * Returns whether this address is a site-local multicast address or not.
639     *
640     * <p>Valid IPv6 site-local multicast addresses have the prefix {@code ffx5::/16},
641     * where x is a set of flags and the additional 112 bits make up the link-local multicast
642     * address space.
643     *
644     * <p>Valid IPv4 site-local multicast addresses have the prefix {@code 239.255/16}.
645     */
646    public boolean isMCSiteLocal() {
647        return false;
648    }
649
650    /**
651     * Returns whether this address is a multicast address or not.
652     *
653     * <p>Valid IPv6 multicast addresses have the prefix {@code ff::/8}.
654     *
655     * <p>Valid IPv4 multicast addresses have the prefix {@code 224/4}.
656     */
657    public boolean isMulticastAddress() {
658        return false;
659    }
660
661    /**
662     * Returns whether this address is a site-local address or not.
663     *
664     * <p>For the purposes of this method, valid IPv6 site-local addresses have
665     * the deprecated prefix {@code fec0::/10} from
666     * <a href="http://www.ietf.org/rfc/rfc1884.txt">RFC 1884</a>,
667     * <i>not</i> the modern prefix {@code fc00::/7} from
668     * <a href="http://www.ietf.org/rfc/rfc4193.txt">RFC 4193</a>.
669     *
670     * <p><a href="http://www.ietf.org/rfc/rfc3484.txt">RFC 3484</a>
671     * "Default Address Selection for Internet Protocol Version 6 (IPv6)" states
672     * that IPv4 private addresses have the prefix {@code 10/8}, {@code 172.16/12},
673     * or {@code 192.168/16}.
674     *
675     * @return {@code true} if this instance represents a site-local address,
676     *         {@code false} otherwise.
677     */
678    public boolean isSiteLocalAddress() {
679        return false;
680    }
681
682    /**
683     * Tries to reach this {@code InetAddress}. This method first tries to use
684     * ICMP <i>(ICMP ECHO REQUEST)</i>, falling back to a TCP connection
685     * on port 7 (Echo) of the remote host.
686     *
687     * @param timeout
688     *            timeout in milliseconds before the test fails if no connection
689     *            could be established.
690     * @return {@code true} if this address is reachable, {@code false}
691     *         otherwise.
692     * @throws IOException
693     *             if an error occurs during an I/O operation.
694     * @throws IllegalArgumentException
695     *             if timeout is less than zero.
696     */
697    public boolean isReachable(int timeout) throws IOException {
698        return isReachable(null, 0, timeout);
699    }
700
701    /**
702     * Tries to reach this {@code InetAddress}. This method first tries to use
703     * ICMP <i>(ICMP ECHO REQUEST)</i>, falling back to a TCP connection
704     * on port 7 (Echo) of the remote host.
705     *
706     * @param networkInterface
707     *            the network interface on which to connection should be
708     *            established.
709     * @param ttl
710     *            the maximum count of hops (time-to-live).
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 ttl or timeout is less than zero.
720     */
721    public boolean isReachable(NetworkInterface networkInterface, final int ttl, final int timeout) throws IOException {
722        if (ttl < 0 || timeout < 0) {
723            throw new IllegalArgumentException("ttl < 0 || timeout < 0");
724        }
725
726        // The simple case.
727        if (networkInterface == null) {
728            return isReachable(this, null, timeout);
729        }
730
731        // Try each NetworkInterface in parallel.
732        // Use a thread pool Executor?
733        List<InetAddress> sourceAddresses = Collections.list(networkInterface.getInetAddresses());
734        if (sourceAddresses.isEmpty()) {
735            return false;
736        }
737        final InetAddress destinationAddress = this;
738        final CountDownLatch latch = new CountDownLatch(sourceAddresses.size());
739        final AtomicBoolean isReachable = new AtomicBoolean(false);
740        for (final InetAddress sourceAddress : sourceAddresses) {
741            new Thread() {
742                @Override public void run() {
743                    try {
744                        if (isReachable(destinationAddress, sourceAddress, timeout)) {
745                            isReachable.set(true);
746                            // Wake the main thread so it can return success without
747                            // waiting for any other threads to time out.
748                            while (latch.getCount() > 0) {
749                                latch.countDown();
750                            }
751                        }
752                    } catch (IOException ignored) {
753                    }
754                    latch.countDown();
755                }
756            }.start();
757        }
758        try {
759            latch.await();
760        } catch (InterruptedException ignored) {
761            Thread.currentThread().interrupt(); // Leave the interrupted bit set.
762        }
763        return isReachable.get();
764    }
765
766    private boolean isReachable(InetAddress destination, InetAddress source, int timeout) throws IOException {
767        // TODO: try ICMP first (http://code.google.com/p/android/issues/detail?id=20106)
768        FileDescriptor fd = IoBridge.socket(true);
769        boolean reached = false;
770        try {
771            if (source != null) {
772                IoBridge.bind(fd, source, 0);
773            }
774            IoBridge.connect(fd, destination, 7, timeout);
775            reached = true;
776        } catch (IOException e) {
777            if (e.getCause() instanceof ErrnoException) {
778                // "Connection refused" means the IP address was reachable.
779                reached = (((ErrnoException) e.getCause()).errno == ECONNREFUSED);
780            }
781        }
782
783        IoBridge.closeAndSignalBlockedThreads(fd);
784
785        return reached;
786    }
787
788    /**
789     * Equivalent to {@code getByAddress(null, ipAddress)}. Handy for addresses with
790     * no associated hostname.
791     */
792    public static InetAddress getByAddress(byte[] ipAddress) throws UnknownHostException {
793        return getByAddress(null, ipAddress, 0);
794    }
795
796    /**
797     * Returns an {@code InetAddress} corresponding to the given network-order
798     * bytes {@code ipAddress} and {@code scopeId}.
799     *
800     * <p>For an IPv4 address, the byte array must be of length 4.
801     * For IPv6, the byte array must be of length 16. Any other length will cause an {@code
802     * UnknownHostException}.
803     *
804     * <p>No reverse lookup is performed. The given {@code hostName} (which may be null) is
805     * associated with the new {@code InetAddress} with no validation done.
806     *
807     * <p>(Note that numeric addresses such as {@code "127.0.0.1"} are names for the
808     * purposes of this API. Most callers probably want {@link #getAllByName} instead.)
809     *
810     * @throws UnknownHostException if {@code ipAddress} is null or the wrong length.
811     */
812    public static InetAddress getByAddress(String hostName, byte[] ipAddress) throws UnknownHostException {
813        return getByAddress(hostName, ipAddress, 0);
814    }
815
816    private static InetAddress getByAddress(String hostName, byte[] ipAddress, int scopeId) throws UnknownHostException {
817        if (ipAddress == null) {
818            throw new UnknownHostException("ipAddress == null");
819        }
820        if (ipAddress.length == 4) {
821            return new Inet4Address(ipAddress.clone(), hostName);
822        } else if (ipAddress.length == 16) {
823            // First check to see if the address is an IPv6-mapped
824            // IPv4 address. If it is, then we can make it a IPv4
825            // address, otherwise, we'll create an IPv6 address.
826            if (isIPv4MappedAddress(ipAddress)) {
827                return new Inet4Address(ipv4MappedToIPv4(ipAddress), hostName);
828            } else {
829                return new Inet6Address(ipAddress.clone(), hostName, scopeId);
830            }
831        } else {
832            throw badAddressLength(ipAddress);
833        }
834    }
835
836    private static UnknownHostException badAddressLength(byte[] bytes) throws UnknownHostException {
837        throw new UnknownHostException("Address is neither 4 or 16 bytes: " + Arrays.toString(bytes));
838    }
839
840    private static boolean isIPv4MappedAddress(byte[] ipAddress) {
841        // Check if the address matches ::FFFF:d.d.d.d
842        // The first 10 bytes are 0. The next to are -1 (FF).
843        // The last 4 bytes are varied.
844        if (ipAddress == null || ipAddress.length != 16) {
845            return false;
846        }
847        for (int i = 0; i < 10; i++) {
848            if (ipAddress[i] != 0) {
849                return false;
850            }
851        }
852        if (ipAddress[10] != -1 || ipAddress[11] != -1) {
853            return false;
854        }
855        return true;
856    }
857
858    private static byte[] ipv4MappedToIPv4(byte[] mappedAddress) {
859        byte[] ipv4Address = new byte[4];
860        for (int i = 0; i < 4; i++) {
861            ipv4Address[i] = mappedAddress[12 + i];
862        }
863        return ipv4Address;
864    }
865
866    private static final ObjectStreamField[] serialPersistentFields = {
867        new ObjectStreamField("address", int.class),
868        new ObjectStreamField("family", int.class),
869        new ObjectStreamField("hostName", String.class),
870    };
871
872    private void writeObject(ObjectOutputStream stream) throws IOException {
873        ObjectOutputStream.PutField fields = stream.putFields();
874        if (ipaddress == null) {
875            fields.put("address", 0);
876        } else {
877            fields.put("address", Memory.peekInt(ipaddress, 0, ByteOrder.BIG_ENDIAN));
878        }
879        fields.put("family", family);
880        fields.put("hostName", hostName);
881
882        stream.writeFields();
883    }
884
885    private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
886        ObjectInputStream.GetField fields = stream.readFields();
887        int addr = fields.get("address", 0);
888        ipaddress = new byte[4];
889        Memory.pokeInt(ipaddress, 0, addr, ByteOrder.BIG_ENDIAN);
890        hostName = (String) fields.get("hostName", null);
891        family = fields.get("family", 2);
892    }
893
894    /*
895     * The spec requires that if we encounter a generic InetAddress in
896     * serialized form then we should interpret it as an Inet4Address.
897     */
898    private Object readResolve() throws ObjectStreamException {
899        return new Inet4Address(ipaddress, hostName);
900    }
901}
902