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