InetAddress.java revision c2614bb1297234d89f1a428a8b589bb1373a68dd
1/*
2 * Copyright (C) 2014 The Android Open Source Project
3 * Copyright (c) 1995, 2011, Oracle and/or its affiliates. All rights reserved.
4 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5 *
6 * This code is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License version 2 only, as
8 * published by the Free Software Foundation.  Oracle designates this
9 * particular file as subject to the "Classpath" exception as provided
10 * by Oracle in the LICENSE file that accompanied this code.
11 *
12 * This code is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 * version 2 for more details (a copy is included in the LICENSE file that
16 * accompanied this code).
17 *
18 * You should have received a copy of the GNU General Public License version
19 * 2 along with this work; if not, write to the Free Software Foundation,
20 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
21 *
22 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
23 * or visit www.oracle.com if you need additional information or have any
24 * questions.
25 */
26
27package java.net;
28
29import java.io.ObjectStreamException;
30import java.io.ObjectStreamField;
31import java.io.IOException;
32import java.io.ObjectInputStream;
33import java.io.ObjectInputStream.GetField;
34import java.io.ObjectOutputStream;
35import java.io.ObjectOutputStream.PutField;
36import sun.net.util.IPAddressUtil;
37import sun.net.spi.nameservice.*;
38import android.system.GaiException;
39import android.system.StructAddrinfo;
40import libcore.io.Libcore;
41import static android.system.OsConstants.*;
42
43/**
44 * This class represents an Internet Protocol (IP) address.
45 *
46 * <p> An IP address is either a 32-bit or 128-bit unsigned number
47 * used by IP, a lower-level protocol on which protocols like UDP and
48 * TCP are built. The IP address architecture is defined by <a
49 * href="http://www.ietf.org/rfc/rfc790.txt"><i>RFC&nbsp;790:
50 * Assigned Numbers</i></a>, <a
51 * href="http://www.ietf.org/rfc/rfc1918.txt"> <i>RFC&nbsp;1918:
52 * Address Allocation for Private Internets</i></a>, <a
53 * href="http://www.ietf.org/rfc/rfc2365.txt"><i>RFC&nbsp;2365:
54 * Administratively Scoped IP Multicast</i></a>, and <a
55 * href="http://www.ietf.org/rfc/rfc2373.txt"><i>RFC&nbsp;2373: IP
56 * Version 6 Addressing Architecture</i></a>. An instance of an
57 * InetAddress consists of an IP address and possibly its
58 * corresponding host name (depending on whether it is constructed
59 * with a host name or whether it has already done reverse host name
60 * resolution).
61 *
62 * <h4> Address types </h4>
63 *
64 * <blockquote><table cellspacing=2 summary="Description of unicast and multicast address types">
65 *   <tr><th valign=top><i>unicast</i></th>
66 *       <td>An identifier for a single interface. A packet sent to
67 *         a unicast address is delivered to the interface identified by
68 *         that address.
69 *
70 *         <p> The Unspecified Address -- Also called anylocal or wildcard
71 *         address. It must never be assigned to any node. It indicates the
72 *         absence of an address. One example of its use is as the target of
73 *         bind, which allows a server to accept a client connection on any
74 *         interface, in case the server host has multiple interfaces.
75 *
76 *         <p> The <i>unspecified</i> address must not be used as
77 *         the destination address of an IP packet.
78 *
79 *         <p> The <i>Loopback</i> Addresses -- This is the address
80 *         assigned to the loopback interface. Anything sent to this
81 *         IP address loops around and becomes IP input on the local
82 *         host. This address is often used when testing a
83 *         client.</td></tr>
84 *   <tr><th valign=top><i>multicast</i></th>
85 *       <td>An identifier for a set of interfaces (typically belonging
86 *         to different nodes). A packet sent to a multicast address is
87 *         delivered to all interfaces identified by that address.</td></tr>
88 * </table></blockquote>
89 *
90 * <h4> IP address scope </h4>
91 *
92 * <p> <i>Link-local</i> addresses are designed to be used for addressing
93 * on a single link for purposes such as auto-address configuration,
94 * neighbor discovery, or when no routers are present.
95 *
96 * <p> <i>Site-local</i> addresses are designed to be used for addressing
97 * inside of a site without the need for a global prefix.
98 *
99 * <p> <i>Global</i> addresses are unique across the internet.
100 *
101 * <h4> Textual representation of IP addresses </h4>
102 *
103 * The textual representation of an IP address is address family specific.
104 *
105 * <p>
106 *
107 * For IPv4 address format, please refer to <A
108 * HREF="Inet4Address.html#format">Inet4Address#format</A>; For IPv6
109 * address format, please refer to <A
110 * HREF="Inet6Address.html#format">Inet6Address#format</A>.
111 *
112 * <P>There is a <a href="doc-files/net-properties.html#Ipv4IPv6">couple of
113 * System Properties</a> affecting how IPv4 and IPv6 addresses are used.</P>
114 *
115 * <h4> Host Name Resolution </h4>
116 *
117 * Host name-to-IP address <i>resolution</i> is accomplished through
118 * the use of a combination of local machine configuration information
119 * and network naming services such as the Domain Name System (DNS)
120 * and Network Information Service(NIS). The particular naming
121 * services(s) being used is by default the local machine configured
122 * one. For any host name, its corresponding IP address is returned.
123 *
124 * <p> <i>Reverse name resolution</i> means that for any IP address,
125 * the host associated with the IP address is returned.
126 *
127 * <p> The InetAddress class provides methods to resolve host names to
128 * their IP addresses and vice versa.
129 *
130 * <h4> InetAddress Caching </h4>
131 *
132 * The InetAddress class has a cache to store successful as well as
133 * unsuccessful host name resolutions.
134 *
135 * <p> By default, when a security manager is installed, in order to
136 * protect against DNS spoofing attacks,
137 * the result of positive host name resolutions are
138 * cached forever. When a security manager is not installed, the default
139 * behavior is to cache entries for a finite (implementation dependent)
140 * period of time. The result of unsuccessful host
141 * name resolution is cached for a very short period of time (10
142 * seconds) to improve performance.
143 *
144 * <p> If the default behavior is not desired, then a Java security property
145 * can be set to a different Time-to-live (TTL) value for positive
146 * caching. Likewise, a system admin can configure a different
147 * negative caching TTL value when needed.
148 *
149 * <p> Two Java security properties control the TTL values used for
150 *  positive and negative host name resolution caching:
151 *
152 * <blockquote>
153 * <dl>
154 * <dt><b>networkaddress.cache.ttl</b></dt>
155 * <dd>Indicates the caching policy for successful name lookups from
156 * the name service. The value is specified as as integer to indicate
157 * the number of seconds to cache the successful lookup. The default
158 * setting is to cache for an implementation specific period of time.
159 * <p>
160 * A value of -1 indicates "cache forever".
161 * </dd>
162 * <p>
163 * <dt><b>networkaddress.cache.negative.ttl</b> (default: 10)</dt>
164 * <dd>Indicates the caching policy for un-successful name lookups
165 * from the name service. The value is specified as as integer to
166 * indicate the number of seconds to cache the failure for
167 * un-successful lookups.
168 * <p>
169 * A value of 0 indicates "never cache".
170 * A value of -1 indicates "cache forever".
171 * </dd>
172 * </dl>
173 * </blockquote>
174 *
175 * @author  Chris Warth
176 * @see     java.net.InetAddress#getByAddress(byte[])
177 * @see     java.net.InetAddress#getByAddress(java.lang.String, byte[])
178 * @see     java.net.InetAddress#getAllByName(java.lang.String)
179 * @see     java.net.InetAddress#getByName(java.lang.String)
180 * @see     java.net.InetAddress#getLocalHost()
181 * @since JDK1.0
182 */
183public
184class InetAddress implements java.io.Serializable {
185
186    static class InetAddressHolder {
187
188        InetAddressHolder() {}
189
190        InetAddressHolder(String hostName, int address, int family) {
191            this.hostName = hostName;
192            this.address = address;
193            this.family = family;
194        }
195
196        String hostName;
197
198        String getHostName() {
199            return hostName;
200        }
201
202        /**
203         * Holds a 32-bit IPv4 address.
204         */
205        int address;
206
207        int getAddress() {
208            return address;
209        }
210
211        /**
212         * Specifies the address family type, for instance, AF_INET for IPv4
213         * addresses, and AF_INET6 for IPv6 addresses.
214         */
215        int family;
216
217        int getFamily() {
218            return family;
219        }
220    }
221
222    transient InetAddressHolder holder;
223
224    InetAddressHolder holder() {
225        return holder;
226    }
227
228    /* The implementation is always dual stack IPv6/IPv4 on android */
229    static final InetAddressImpl impl = new Inet6AddressImpl();
230
231    /* Used to store the name service provider */
232    private static final NameService nameService = new NameService() {
233        public InetAddress[] lookupAllHostAddr(String host, int netId)
234                throws UnknownHostException {
235            return impl.lookupAllHostAddr(host, netId);
236        }
237        public String getHostByAddr(byte[] addr)
238                throws UnknownHostException {
239            return impl.getHostByAddr(addr);
240        }
241    };
242
243    /* Used to store the best available hostname */
244    private transient String canonicalHostName = null;
245
246    /** use serialVersionUID from JDK 1.0.2 for interoperability */
247    private static final long serialVersionUID = 3286316764910316507L;
248
249    /*
250     * Load net library into runtime, and perform initializations.
251     */
252    static {
253        init();
254    }
255
256    /**
257     * Constructor for the Socket.accept() method.
258     * This creates an empty InetAddress, which is filled in by
259     * the accept() method.  This InetAddress, however, is not
260     * put in the address cache, since it is not created by name.
261     */
262    InetAddress() {
263        holder = new InetAddressHolder();
264    }
265
266    /**
267     * Replaces the de-serialized object with an Inet4Address object.
268     *
269     * @return the alternate object to the de-serialized object.
270     *
271     * @throws ObjectStreamException if a new object replacing this
272     * object could not be created
273     */
274    private Object readResolve() throws ObjectStreamException {
275        // will replace the deserialized 'this' object
276        return new Inet4Address(holder().getHostName(), holder().getAddress());
277    }
278
279    /**
280     * Utility routine to check if the InetAddress is an
281     * IP multicast address.
282     * @return a <code>boolean</code> indicating if the InetAddress is
283     * an IP multicast address
284     * @since   JDK1.1
285     */
286    public boolean isMulticastAddress() {
287        return false;
288    }
289
290    /**
291     * Utility routine to check if the InetAddress in a wildcard address.
292     * @return a <code>boolean</code> indicating if the Inetaddress is
293     *         a wildcard address.
294     * @since 1.4
295     */
296    public boolean isAnyLocalAddress() {
297        return false;
298    }
299
300    /**
301     * Utility routine to check if the InetAddress is a loopback address.
302     *
303     * @return a <code>boolean</code> indicating if the InetAddress is
304     * a loopback address; or false otherwise.
305     * @since 1.4
306     */
307    public boolean isLoopbackAddress() {
308        return false;
309    }
310
311    /**
312     * Utility routine to check if the InetAddress is an link local address.
313     *
314     * @return a <code>boolean</code> indicating if the InetAddress is
315     * a link local address; or false if address is not a link local unicast address.
316     * @since 1.4
317     */
318    public boolean isLinkLocalAddress() {
319        return false;
320    }
321
322    /**
323     * Utility routine to check if the InetAddress is a site local address.
324     *
325     * @return a <code>boolean</code> indicating if the InetAddress is
326     * a site local address; or false if address is not a site local unicast address.
327     * @since 1.4
328     */
329    public boolean isSiteLocalAddress() {
330        return false;
331    }
332
333    /**
334     * Utility routine to check if the multicast address has global scope.
335     *
336     * @return a <code>boolean</code> indicating if the address has
337     *         is a multicast address of global scope, false if it is not
338     *         of global scope or it is not a multicast address
339     * @since 1.4
340     */
341    public boolean isMCGlobal() {
342        return false;
343    }
344
345    /**
346     * Utility routine to check if the multicast address has node scope.
347     *
348     * @return a <code>boolean</code> indicating if the address has
349     *         is a multicast address of node-local scope, false if it is not
350     *         of node-local scope or it is not a multicast address
351     * @since 1.4
352     */
353    public boolean isMCNodeLocal() {
354        return false;
355    }
356
357    /**
358     * Utility routine to check if the multicast address has link scope.
359     *
360     * @return a <code>boolean</code> indicating if the address has
361     *         is a multicast address of link-local scope, false if it is not
362     *         of link-local scope or it is not a multicast address
363     * @since 1.4
364     */
365    public boolean isMCLinkLocal() {
366        return false;
367    }
368
369    /**
370     * Utility routine to check if the multicast address has site scope.
371     *
372     * @return a <code>boolean</code> indicating if the address has
373     *         is a multicast address of site-local scope, false if it is not
374     *         of site-local scope or it is not a multicast address
375     * @since 1.4
376     */
377    public boolean isMCSiteLocal() {
378        return false;
379    }
380
381    /**
382     * Utility routine to check if the multicast address has organization scope.
383     *
384     * @return a <code>boolean</code> indicating if the address has
385     *         is a multicast address of organization-local scope,
386     *         false if it is not of organization-local scope
387     *         or it is not a multicast address
388     * @since 1.4
389     */
390    public boolean isMCOrgLocal() {
391        return false;
392    }
393
394
395    /**
396     * Test whether that address is reachable. Best effort is made by the
397     * implementation to try to reach the host, but firewalls and server
398     * configuration may block requests resulting in a unreachable status
399     * while some specific ports may be accessible.
400     * A typical implementation will use ICMP ECHO REQUESTs if the
401     * privilege can be obtained, otherwise it will try to establish
402     * a TCP connection on port 7 (Echo) of the destination host.
403     * <p>
404     * The timeout value, in milliseconds, indicates the maximum amount of time
405     * the try should take. If the operation times out before getting an
406     * answer, the host is deemed unreachable. A negative value will result
407     * in an IllegalArgumentException being thrown.
408     *
409     * @param   timeout the time, in milliseconds, before the call aborts
410     * @return a <code>boolean</code> indicating if the address is reachable.
411     * @throws IOException if a network error occurs
412     * @throws  IllegalArgumentException if <code>timeout</code> is negative.
413     * @since 1.5
414     */
415    public boolean isReachable(int timeout) throws IOException {
416        return isReachable(null, 0, timeout);
417    }
418
419    /**
420     * Test whether that address is reachable. Best effort is made by the
421     * implementation to try to reach the host, but firewalls and server
422     * configuration may block requests resulting in a unreachable status
423     * while some specific ports may be accessible.
424     * A typical implementation will use ICMP ECHO REQUESTs if the
425     * privilege can be obtained, otherwise it will try to establish
426     * a TCP connection on port 7 (Echo) of the destination host.
427     * <p>
428     * The <code>network interface</code> and <code>ttl</code> parameters
429     * let the caller specify which network interface the test will go through
430     * and the maximum number of hops the packets should go through.
431     * A negative value for the <code>ttl</code> will result in an
432     * IllegalArgumentException being thrown.
433     * <p>
434     * The timeout value, in milliseconds, indicates the maximum amount of time
435     * the try should take. If the operation times out before getting an
436     * answer, the host is deemed unreachable. A negative value will result
437     * in an IllegalArgumentException being thrown.
438     *
439     * @param   netif   the NetworkInterface through which the
440     *                    test will be done, or null for any interface
441     * @param   ttl     the maximum numbers of hops to try or 0 for the
442     *                  default
443     * @param   timeout the time, in milliseconds, before the call aborts
444     * @throws  IllegalArgumentException if either <code>timeout</code>
445     *                          or <code>ttl</code> are negative.
446     * @return a <code>boolean</code>indicating if the address is reachable.
447     * @throws IOException if a network error occurs
448     * @since 1.5
449     */
450    public boolean isReachable(NetworkInterface netif, int ttl,
451                               int timeout) throws IOException {
452        if (ttl < 0)
453            throw new IllegalArgumentException("ttl can't be negative");
454        if (timeout < 0)
455            throw new IllegalArgumentException("timeout can't be negative");
456
457        return impl.isReachable(this, timeout, netif, ttl);
458    }
459
460    /**
461     * Gets the host name for this IP address.
462     *
463     * <p>If this InetAddress was created with a host name,
464     * this host name will be remembered and returned;
465     * otherwise, a reverse name lookup will be performed
466     * and the result will be returned based on the system
467     * configured name lookup service. If a lookup of the name service
468     * is required, call
469     * {@link #getCanonicalHostName() getCanonicalHostName}.
470     *
471     * <p>If there is a security manager, its
472     * <code>checkConnect</code> method is first called
473     * with the hostname and <code>-1</code>
474     * as its arguments to see if the operation is allowed.
475     * If the operation is not allowed, it will return
476     * the textual representation of the IP address.
477     *
478     * @return  the host name for this IP address, or if the operation
479     *    is not allowed by the security check, the textual
480     *    representation of the IP address.
481     *
482     * @see InetAddress#getCanonicalHostName
483     * @see SecurityManager#checkConnect
484     */
485    public String getHostName() {
486        if (holder().getHostName() == null) {
487            holder().hostName = InetAddress.getHostFromNameService(this);
488        }
489        return holder().getHostName();
490    }
491
492    /**
493     * Gets the fully qualified domain name for this IP address.
494     * Best effort method, meaning we may not be able to return
495     * the FQDN depending on the underlying system configuration.
496     *
497     * <p>If there is a security manager, this method first
498     * calls its <code>checkConnect</code> method
499     * with the hostname and <code>-1</code>
500     * as its arguments to see if the calling code is allowed to know
501     * the hostname for this IP address, i.e., to connect to the host.
502     * If the operation is not allowed, it will return
503     * the textual representation of the IP address.
504     *
505     * @return  the fully qualified domain name for this IP address,
506     *    or if the operation is not allowed by the security check,
507     *    the textual representation of the IP address.
508     *
509     * @see SecurityManager#checkConnect
510     *
511     * @since 1.4
512     */
513    public String getCanonicalHostName() {
514        if (canonicalHostName == null) {
515            canonicalHostName = InetAddress.getHostFromNameService(this);
516        }
517        return canonicalHostName;
518    }
519
520    /**
521     * Returns the hostname for this address.
522     *
523     * <p>If there is a security manager, this method first
524     * calls its <code>checkConnect</code> method
525     * with the hostname and <code>-1</code>
526     * as its arguments to see if the calling code is allowed to know
527     * the hostname for this IP address, i.e., to connect to the host.
528     * If the operation is not allowed, it will return
529     * the textual representation of the IP address.
530     *
531     * @return  the host name for this IP address, or if the operation
532     *    is not allowed by the security check, the textual
533     *    representation of the IP address.
534     *
535     * @see SecurityManager#checkConnect
536     */
537    private static String getHostFromNameService(InetAddress addr) {
538        String host = null;
539        try {
540            // first lookup the hostname
541            host = nameService.getHostByAddr(addr.getAddress());
542
543                /* now get all the IP addresses for this hostname,
544                 * and make sure one of them matches the original IP
545                 * address. We do this to try and prevent spoofing.
546                 */
547            InetAddress[] arr = nameService.lookupAllHostAddr(host, NETID_UNSET);
548            boolean ok = false;
549
550            if (arr != null) {
551                for(int i = 0; !ok && i < arr.length; i++) {
552                    ok = addr.equals(arr[i]);
553                }
554            }
555
556            //XXX: if it looks a spoof just return the address?
557            if (!ok) {
558                host = addr.getHostAddress();
559                return host;
560            }
561        } catch (UnknownHostException e) {
562            host = addr.getHostAddress();
563        }
564
565        return host;
566    }
567
568    /**
569     * Returns the raw IP address of this <code>InetAddress</code>
570     * object. The result is in network byte order: the highest order
571     * byte of the address is in <code>getAddress()[0]</code>.
572     *
573     * @return  the raw IP address of this object.
574     */
575    public byte[] getAddress() {
576        return null;
577    }
578
579    /**
580     * Called from native code. Same as {@code getAddress}, but for internal users.
581     *
582     * @return
583     */
584    public byte[] getAddressInternal() {
585        return null;
586    }
587
588
589    /**
590     * Returns the IP address string in textual presentation.
591     *
592     * @return  the raw IP address in a string format.
593     * @since   JDK1.0.2
594     */
595    public String getHostAddress() {
596        return null;
597     }
598
599    /**
600     * Returns a hashcode for this IP address.
601     *
602     * @return  a hash code value for this IP address.
603     */
604    public int hashCode() {
605        return -1;
606    }
607
608    /**
609     * Compares this object against the specified object.
610     * The result is <code>true</code> if and only if the argument is
611     * not <code>null</code> and it represents the same IP address as
612     * this object.
613     * <p>
614     * Two instances of <code>InetAddress</code> represent the same IP
615     * address if the length of the byte arrays returned by
616     * <code>getAddress</code> is the same for both, and each of the
617     * array components is the same for the byte arrays.
618     *
619     * @param   obj   the object to compare against.
620     * @return  <code>true</code> if the objects are the same;
621     *          <code>false</code> otherwise.
622     * @see     java.net.InetAddress#getAddress()
623     */
624    public boolean equals(Object obj) {
625        return false;
626    }
627
628    /**
629     * Converts this IP address to a <code>String</code>. The
630     * string returned is of the form: hostname / literal IP
631     * address.
632     *
633     * If the host name is unresolved, no reverse name service lookup
634     * is performed. The hostname part will be represented by an empty string.
635     *
636     * @return  a string representation of this IP address.
637     */
638    public String toString() {
639        String hostName = holder().getHostName();
640        return ((hostName != null) ? hostName : "")
641            + "/" + getHostAddress();
642    }
643
644    /**
645     * Creates an InetAddress based on the provided host name and IP address.
646     * No name service is checked for the validity of the address.
647     *
648     * <p> The host name can either be a machine name, such as
649     * "<code>java.sun.com</code>", or a textual representation of its IP
650     * address.
651     * <p> No validity checking is done on the host name either.
652     *
653     * <p> If addr specifies an IPv4 address an instance of Inet4Address
654     * will be returned; otherwise, an instance of Inet6Address
655     * will be returned.
656     *
657     * <p> IPv4 address byte array must be 4 bytes long and IPv6 byte array
658     * must be 16 bytes long
659     *
660     * @param host the specified host
661     * @param addr the raw IP address in network byte order
662     * @return  an InetAddress object created from the raw IP address.
663     * @exception  UnknownHostException  if IP address is of illegal length
664     * @since 1.4
665     */
666    public static InetAddress getByAddress(String host, byte[] addr) throws UnknownHostException {
667        return getByAddress(host, addr, -1 /* scopeId */);
668    }
669
670    // Do not delete. Called from native code.
671    private static InetAddress getByAddress(String host, byte[] addr, int scopeId)
672        throws UnknownHostException {
673        if (host != null && host.length() > 0 && host.charAt(0) == '[') {
674            if (host.charAt(host.length()-1) == ']') {
675                host = host.substring(1, host.length() -1);
676            }
677        }
678        if (addr != null) {
679            if (addr.length == Inet4Address.INADDRSZ) {
680                return new Inet4Address(host, addr);
681            } else if (addr.length == Inet6Address.INADDRSZ) {
682                byte[] newAddr
683                    = IPAddressUtil.convertFromIPv4MappedAddress(addr);
684                if (newAddr != null) {
685                    return new Inet4Address(host, newAddr);
686                } else {
687                    return new Inet6Address(host, addr, scopeId);
688                }
689            }
690        }
691        throw new UnknownHostException("addr is of illegal length");
692    }
693
694
695    /**
696     * Determines the IP address of a host, given the host's name.
697     *
698     * <p> The host name can either be a machine name, such as
699     * "<code>java.sun.com</code>", or a textual representation of its
700     * IP address. If a literal IP address is supplied, only the
701     * validity of the address format is checked.
702     *
703     * <p> For <code>host</code> specified in literal IPv6 address,
704     * either the form defined in RFC 2732 or the literal IPv6 address
705     * format defined in RFC 2373 is accepted. IPv6 scoped addresses are also
706     * supported. See <a href="Inet6Address.html#scoped">here</a> for a description of IPv6
707     * scoped addresses.
708     *
709     * <p> If the host is <tt>null</tt> then an <tt>InetAddress</tt>
710     * representing an address of the loopback interface is returned.
711     * See <a href="http://www.ietf.org/rfc/rfc3330.txt">RFC&nbsp;3330</a>
712     * section&nbsp;2 and <a href="http://www.ietf.org/rfc/rfc2373.txt">RFC&nbsp;2373</a>
713     * section&nbsp;2.5.3. </p>
714     *
715     * @param      host   the specified host, or <code>null</code>.
716     * @return     an IP address for the given host name.
717     * @exception  UnknownHostException  if no IP address for the
718     *               <code>host</code> could be found, or if a scope_id was specified
719     *               for a global IPv6 address.
720     * @exception  SecurityException if a security manager exists
721     *             and its checkConnect method doesn't allow the operation
722     */
723    public static InetAddress getByName(String host)
724        throws UnknownHostException {
725        return InetAddress.getAllByName(host)[0];
726    }
727
728    /**
729     * Given the name of a host, returns an array of its IP addresses,
730     * based on the configured name service on the system.
731     *
732     * <p> The host name can either be a machine name, such as
733     * "<code>java.sun.com</code>", or a textual representation of its IP
734     * address. If a literal IP address is supplied, only the
735     * validity of the address format is checked.
736     *
737     * <p> For <code>host</code> specified in <i>literal IPv6 address</i>,
738     * either the form defined in RFC 2732 or the literal IPv6 address
739     * format defined in RFC 2373 is accepted. A literal IPv6 address may
740     * also be qualified by appending a scoped zone identifier or scope_id.
741     * The syntax and usage of scope_ids is described
742     * <a href="Inet6Address.html#scoped">here</a>.
743     * <p> If the host is <tt>null</tt> then an <tt>InetAddress</tt>
744     * representing an address of the loopback interface is returned.
745     * See <a href="http://www.ietf.org/rfc/rfc3330.txt">RFC&nbsp;3330</a>
746     * section&nbsp;2 and <a href="http://www.ietf.org/rfc/rfc2373.txt">RFC&nbsp;2373</a>
747     * section&nbsp;2.5.3. </p>
748     *
749     * <p> If there is a security manager and <code>host</code> is not
750     * null and <code>host.length() </code> is not equal to zero, the
751     * security manager's
752     * <code>checkConnect</code> method is called
753     * with the hostname and <code>-1</code>
754     * as its arguments to see if the operation is allowed.
755     *
756     * @param      host   the name of the host, or <code>null</code>.
757     * @return     an array of all the IP addresses for a given host name.
758     *
759     * @exception  UnknownHostException  if no IP address for the
760     *               <code>host</code> could be found, or if a scope_id was specified
761     *               for a global IPv6 address.
762     * @exception  SecurityException  if a security manager exists and its
763     *               <code>checkConnect</code> method doesn't allow the operation.
764     *
765     * @see SecurityManager#checkConnect
766     */
767    public static InetAddress[] getAllByName(String host)
768        throws UnknownHostException {
769        return impl.lookupAllHostAddr(host, NETID_UNSET);
770    }
771
772    /**
773     * Returns the loopback address.
774     * <p>
775     * The InetAddress returned will represent the IPv4
776     * loopback address, 127.0.0.1, or the IPv6 loopback
777     * address, ::1. The IPv4 loopback address returned
778     * is only one of many in the form 127.*.*.*
779     *
780     * @return  the InetAddress loopback instance.
781     * @since 1.7
782     */
783    public static InetAddress getLoopbackAddress() {
784        return impl.loopbackAddresses()[0];
785    }
786
787    /**
788     * Returns an <code>InetAddress</code> object given the raw IP address .
789     * The argument is in network byte order: the highest order
790     * byte of the address is in <code>getAddress()[0]</code>.
791     *
792     * <p> This method doesn't block, i.e. no reverse name service lookup
793     * is performed.
794     *
795     * <p> IPv4 address byte array must be 4 bytes long and IPv6 byte array
796     * must be 16 bytes long
797     *
798     * @param addr the raw IP address in network byte order
799     * @return  an InetAddress object created from the raw IP address.
800     * @exception  UnknownHostException  if IP address is of illegal length
801     * @since 1.4
802     */
803    public static InetAddress getByAddress(byte[] addr)
804        throws UnknownHostException {
805        return getByAddress(null, addr);
806    }
807
808    /**
809     * Returns the address of the local host. This is achieved by retrieving
810     * the name of the host from the system, then resolving that name into
811     * an <code>InetAddress</code>.
812     *
813     * <P>Note: The resolved address may be cached for a short period of time.
814     * </P>
815     *
816     * <p>If there is a security manager, its
817     * <code>checkConnect</code> method is called
818     * with the local host name and <code>-1</code>
819     * as its arguments to see if the operation is allowed.
820     * If the operation is not allowed, an InetAddress representing
821     * the loopback address is returned.
822     *
823     * @return     the address of the local host.
824     *
825     * @exception  UnknownHostException  if the local host name could not
826     *             be resolved into an address.
827     *
828     * @see SecurityManager#checkConnect
829     * @see java.net.InetAddress#getByName(java.lang.String)
830     */
831    public static InetAddress getLocalHost() throws UnknownHostException {
832        String local = Libcore.os.uname().nodename;
833        return impl.lookupAllHostAddr(local, NETID_UNSET)[0];
834    }
835
836    /**
837     * Perform class load-time initializations.
838     */
839    private static native void init();
840
841
842    /*
843     * Returns the InetAddress representing anyLocalAddress
844     * (typically 0.0.0.0 or ::0)
845     */
846    static InetAddress anyLocalAddress() {
847        return impl.anyLocalAddress();
848    }
849
850    private void readObjectNoData (ObjectInputStream s) throws
851                         IOException, ClassNotFoundException {
852        // Android-changed : Don't use null to mean the boot classloader.
853        if (getClass().getClassLoader() != BOOT_CLASSLOADER) {
854            throw new SecurityException ("invalid address type");
855        }
856    }
857
858    // Android-changed : Don't use null to mean the boot classloader.
859    private static final ClassLoader BOOT_CLASSLOADER = Object.class.getClassLoader();
860
861    private void readObject (ObjectInputStream s) throws
862                         IOException, ClassNotFoundException {
863        // Android-changed : Don't use null to mean the boot classloader.
864        if (getClass().getClassLoader() != BOOT_CLASSLOADER) {
865            throw new SecurityException ("invalid address type");
866        }
867        GetField gf = s.readFields();
868        String host = (String)gf.get("hostName", null);
869        int address= gf.get("address", 0);
870        int family= gf.get("family", 0);
871        holder = new InetAddressHolder(host, address, family);
872    }
873
874    /* needed because the serializable fields no longer exist */
875
876    /**
877     * @serialField hostName String
878     * @serialField address int
879     * @serialField family int
880     */
881    private static final ObjectStreamField[] serialPersistentFields = {
882        new ObjectStreamField("hostName", String.class),
883        new ObjectStreamField("address", int.class),
884        new ObjectStreamField("family", int.class),
885    };
886
887    private void writeObject (ObjectOutputStream s) throws
888                        IOException {
889        // Android-changed : Don't use null to mean the boot classloader.
890        if (getClass().getClassLoader() != BOOT_CLASSLOADER) {
891            throw new SecurityException ("invalid address type");
892        }
893        PutField pf = s.putFields();
894        pf.put("hostName", holder().hostName);
895        pf.put("address", holder().address);
896        pf.put("family", holder().family);
897        s.writeFields();
898        s.flush();
899    }
900
901    static final int NETID_UNSET = 0;
902
903    /**
904     * Returns true if the string is a valid numeric IPv4 or IPv6 address (such as "192.168.0.1").
905     * This copes with all forms of address that Java supports, detailed in the {@link InetAddress}
906     * class documentation.
907     *
908     * @hide used by frameworks/base to ensure that a getAllByName won't cause a DNS lookup.
909     */
910    public static boolean isNumeric(String address) {
911        InetAddress inetAddress = parseNumericAddressNoThrow(address);
912        return inetAddress != null && disallowDeprecatedFormats(address, inetAddress) != null;
913    }
914
915    static InetAddress parseNumericAddressNoThrow(String address) {
916        // Accept IPv6 addresses (only) in square brackets for compatibility.
917        if (address.startsWith("[") && address.endsWith("]") && address.indexOf(':') != -1) {
918            address = address.substring(1, address.length() - 1);
919        }
920        StructAddrinfo hints = new StructAddrinfo();
921        hints.ai_flags = AI_NUMERICHOST;
922        InetAddress[] addresses = null;
923        try {
924            addresses = Libcore.os.android_getaddrinfo(address, hints, NETID_UNSET);
925        } catch (GaiException ignored) {
926        }
927        return (addresses != null) ? addresses[0] : null;
928    }
929
930    static InetAddress disallowDeprecatedFormats(String address, InetAddress inetAddress) {
931        // Only IPv4 addresses are problematic.
932        if (!(inetAddress instanceof Inet4Address) || address.indexOf(':') != -1) {
933            return inetAddress;
934        }
935        // If inet_pton(3) can't parse it, it must have been a deprecated format.
936        // We need to return inet_pton(3)'s result to ensure that numbers assumed to be octal
937        // by getaddrinfo(3) are reinterpreted by inet_pton(3) as decimal.
938        return Libcore.os.inet_pton(AF_INET, address);
939    }
940
941    /**
942     * Returns an InetAddress corresponding to the given numeric address (such
943     * as {@code "192.168.0.1"} or {@code "2001:4860:800d::68"}).
944     * This method will never do a DNS lookup. Non-numeric addresses are errors.
945     *
946     * @hide used by frameworks/base's NetworkUtils.numericToInetAddress
947     * @throws IllegalArgumentException if {@code numericAddress} is not a numeric address
948     */
949    public static InetAddress parseNumericAddress(String numericAddress) {
950        if (numericAddress == null || numericAddress.isEmpty()) {
951            return Inet6Address.LOOPBACK;
952        }
953        InetAddress result = parseNumericAddressNoThrow(numericAddress);
954        result = disallowDeprecatedFormats(numericAddress, result);
955        if (result == null) {
956            throw new IllegalArgumentException("Not a numeric address: " + numericAddress);
957        }
958        return result;
959    }
960
961    /**
962     * Removes all entries from the VM's DNS cache. This does not affect the C library's DNS
963     * cache, nor any caching DNS servers between you and the canonical server.
964     * @hide
965     */
966    public static void clearDnsCache() {
967        impl.clearAddressCache();
968    }
969
970    /**
971     * Operates identically to {@code getByName} except host resolution is
972     * performed on the network designated by {@code netId}.
973     *
974     * @param host
975     *            the hostName to be resolved to an address or {@code null}.
976     * @param netId the network to use for host resolution.
977     * @return the {@code InetAddress} instance representing the host.
978     * @throws UnknownHostException if the address lookup fails.
979     * @hide internal use only
980     */
981    public static InetAddress getByNameOnNet(String host, int netId) throws UnknownHostException {
982        return impl.lookupAllHostAddr(host, netId)[0];
983    }
984
985    /**
986     * Operates identically to {@code getAllByName} except host resolution is
987     * performed on the network designated by {@code netId}.
988     *
989     * @param host the hostname or literal IP string to be resolved.
990     * @param netId the network to use for host resolution.
991     * @return the array of addresses associated with the specified host.
992     * @throws UnknownHostException if the address lookup fails.
993     * @hide internal use only
994     */
995    public static InetAddress[] getAllByNameOnNet(String host, int netId) throws UnknownHostException {
996        return impl.lookupAllHostAddr(host, netId).clone();
997    }
998
999    // Only called by java.net.SocketPermission.
1000    static InetAddress[] getAllByName0(String authHost, boolean check) throws UnknownHostException {
1001        throw new UnsupportedOperationException();
1002    }
1003
1004    // Only called by java.net.SocketPermission.
1005    String getHostName(boolean check) {
1006        throw new UnsupportedOperationException();
1007    }
1008}