InetAddress.java revision 68b18924acfe6325285eaf01f233ce4b27700763
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     * Returns the IP address string in textual presentation.
581     *
582     * @return  the raw IP address in a string format.
583     * @since   JDK1.0.2
584     */
585    public String getHostAddress() {
586        return null;
587     }
588
589    /**
590     * Returns a hashcode for this IP address.
591     *
592     * @return  a hash code value for this IP address.
593     */
594    public int hashCode() {
595        return -1;
596    }
597
598    /**
599     * Compares this object against the specified object.
600     * The result is <code>true</code> if and only if the argument is
601     * not <code>null</code> and it represents the same IP address as
602     * this object.
603     * <p>
604     * Two instances of <code>InetAddress</code> represent the same IP
605     * address if the length of the byte arrays returned by
606     * <code>getAddress</code> is the same for both, and each of the
607     * array components is the same for the byte arrays.
608     *
609     * @param   obj   the object to compare against.
610     * @return  <code>true</code> if the objects are the same;
611     *          <code>false</code> otherwise.
612     * @see     java.net.InetAddress#getAddress()
613     */
614    public boolean equals(Object obj) {
615        return false;
616    }
617
618    /**
619     * Converts this IP address to a <code>String</code>. The
620     * string returned is of the form: hostname / literal IP
621     * address.
622     *
623     * If the host name is unresolved, no reverse name service lookup
624     * is performed. The hostname part will be represented by an empty string.
625     *
626     * @return  a string representation of this IP address.
627     */
628    public String toString() {
629        String hostName = holder().getHostName();
630        return ((hostName != null) ? hostName : "")
631            + "/" + getHostAddress();
632    }
633
634    /**
635     * Creates an InetAddress based on the provided host name and IP address.
636     * No name service is checked for the validity of the address.
637     *
638     * <p> The host name can either be a machine name, such as
639     * "<code>java.sun.com</code>", or a textual representation of its IP
640     * address.
641     * <p> No validity checking is done on the host name either.
642     *
643     * <p> If addr specifies an IPv4 address an instance of Inet4Address
644     * will be returned; otherwise, an instance of Inet6Address
645     * will be returned.
646     *
647     * <p> IPv4 address byte array must be 4 bytes long and IPv6 byte array
648     * must be 16 bytes long
649     *
650     * @param host the specified host
651     * @param addr the raw IP address in network byte order
652     * @return  an InetAddress object created from the raw IP address.
653     * @exception  UnknownHostException  if IP address is of illegal length
654     * @since 1.4
655     */
656    public static InetAddress getByAddress(String host, byte[] addr) throws UnknownHostException {
657        return getByAddress(host, addr, -1 /* scopeId */);
658    }
659
660    // Do not delete. Called from native code.
661    private static InetAddress getByAddress(String host, byte[] addr, int scopeId)
662        throws UnknownHostException {
663        if (host != null && host.length() > 0 && host.charAt(0) == '[') {
664            if (host.charAt(host.length()-1) == ']') {
665                host = host.substring(1, host.length() -1);
666            }
667        }
668        if (addr != null) {
669            if (addr.length == Inet4Address.INADDRSZ) {
670                return new Inet4Address(host, addr);
671            } else if (addr.length == Inet6Address.INADDRSZ) {
672                byte[] newAddr
673                    = IPAddressUtil.convertFromIPv4MappedAddress(addr);
674                if (newAddr != null) {
675                    return new Inet4Address(host, newAddr);
676                } else {
677                    return new Inet6Address(host, addr, scopeId);
678                }
679            }
680        }
681        throw new UnknownHostException("addr is of illegal length");
682    }
683
684
685    /**
686     * Determines the IP address of a host, given the host's name.
687     *
688     * <p> The host name can either be a machine name, such as
689     * "<code>java.sun.com</code>", or a textual representation of its
690     * IP address. If a literal IP address is supplied, only the
691     * validity of the address format is checked.
692     *
693     * <p> For <code>host</code> specified in literal IPv6 address,
694     * either the form defined in RFC 2732 or the literal IPv6 address
695     * format defined in RFC 2373 is accepted. IPv6 scoped addresses are also
696     * supported. See <a href="Inet6Address.html#scoped">here</a> for a description of IPv6
697     * scoped addresses.
698     *
699     * <p> If the host is <tt>null</tt> then an <tt>InetAddress</tt>
700     * representing an address of the loopback interface is returned.
701     * See <a href="http://www.ietf.org/rfc/rfc3330.txt">RFC&nbsp;3330</a>
702     * section&nbsp;2 and <a href="http://www.ietf.org/rfc/rfc2373.txt">RFC&nbsp;2373</a>
703     * section&nbsp;2.5.3. </p>
704     *
705     * @param      host   the specified host, or <code>null</code>.
706     * @return     an IP address for the given host name.
707     * @exception  UnknownHostException  if no IP address for the
708     *               <code>host</code> could be found, or if a scope_id was specified
709     *               for a global IPv6 address.
710     * @exception  SecurityException if a security manager exists
711     *             and its checkConnect method doesn't allow the operation
712     */
713    public static InetAddress getByName(String host)
714        throws UnknownHostException {
715        return impl.lookupAllHostAddr(host, NETID_UNSET)[0];
716    }
717
718    /**
719     * Given the name of a host, returns an array of its IP addresses,
720     * based on the configured name service on the system.
721     *
722     * <p> The host name can either be a machine name, such as
723     * "<code>java.sun.com</code>", or a textual representation of its IP
724     * address. If a literal IP address is supplied, only the
725     * validity of the address format is checked.
726     *
727     * <p> For <code>host</code> specified in <i>literal IPv6 address</i>,
728     * either the form defined in RFC 2732 or the literal IPv6 address
729     * format defined in RFC 2373 is accepted. A literal IPv6 address may
730     * also be qualified by appending a scoped zone identifier or scope_id.
731     * The syntax and usage of scope_ids is described
732     * <a href="Inet6Address.html#scoped">here</a>.
733     * <p> If the host is <tt>null</tt> then an <tt>InetAddress</tt>
734     * representing an address of the loopback interface is returned.
735     * See <a href="http://www.ietf.org/rfc/rfc3330.txt">RFC&nbsp;3330</a>
736     * section&nbsp;2 and <a href="http://www.ietf.org/rfc/rfc2373.txt">RFC&nbsp;2373</a>
737     * section&nbsp;2.5.3. </p>
738     *
739     * <p> If there is a security manager and <code>host</code> is not
740     * null and <code>host.length() </code> is not equal to zero, the
741     * security manager's
742     * <code>checkConnect</code> method is called
743     * with the hostname and <code>-1</code>
744     * as its arguments to see if the operation is allowed.
745     *
746     * @param      host   the name of the host, or <code>null</code>.
747     * @return     an array of all the IP addresses for a given host name.
748     *
749     * @exception  UnknownHostException  if no IP address for the
750     *               <code>host</code> could be found, or if a scope_id was specified
751     *               for a global IPv6 address.
752     * @exception  SecurityException  if a security manager exists and its
753     *               <code>checkConnect</code> method doesn't allow the operation.
754     *
755     * @see SecurityManager#checkConnect
756     */
757    public static InetAddress[] getAllByName(String host)
758        throws UnknownHostException {
759        return impl.lookupAllHostAddr(host, NETID_UNSET).clone();
760    }
761
762    /**
763     * Returns the loopback address.
764     * <p>
765     * The InetAddress returned will represent the IPv4
766     * loopback address, 127.0.0.1, or the IPv6 loopback
767     * address, ::1. The IPv4 loopback address returned
768     * is only one of many in the form 127.*.*.*
769     *
770     * @return  the InetAddress loopback instance.
771     * @since 1.7
772     */
773    public static InetAddress getLoopbackAddress() {
774        return impl.loopbackAddresses()[0];
775    }
776
777    /**
778     * Returns an <code>InetAddress</code> object given the raw IP address .
779     * The argument is in network byte order: the highest order
780     * byte of the address is in <code>getAddress()[0]</code>.
781     *
782     * <p> This method doesn't block, i.e. no reverse name service lookup
783     * is performed.
784     *
785     * <p> IPv4 address byte array must be 4 bytes long and IPv6 byte array
786     * must be 16 bytes long
787     *
788     * @param addr the raw IP address in network byte order
789     * @return  an InetAddress object created from the raw IP address.
790     * @exception  UnknownHostException  if IP address is of illegal length
791     * @since 1.4
792     */
793    public static InetAddress getByAddress(byte[] addr)
794        throws UnknownHostException {
795        return getByAddress(null, addr);
796    }
797
798    /**
799     * Returns the address of the local host. This is achieved by retrieving
800     * the name of the host from the system, then resolving that name into
801     * an <code>InetAddress</code>.
802     *
803     * <P>Note: The resolved address may be cached for a short period of time.
804     * </P>
805     *
806     * <p>If there is a security manager, its
807     * <code>checkConnect</code> method is called
808     * with the local host name and <code>-1</code>
809     * as its arguments to see if the operation is allowed.
810     * If the operation is not allowed, an InetAddress representing
811     * the loopback address is returned.
812     *
813     * @return     the address of the local host.
814     *
815     * @exception  UnknownHostException  if the local host name could not
816     *             be resolved into an address.
817     *
818     * @see SecurityManager#checkConnect
819     * @see java.net.InetAddress#getByName(java.lang.String)
820     */
821    public static InetAddress getLocalHost() throws UnknownHostException {
822        String local = Libcore.os.uname().nodename;
823        return impl.lookupAllHostAddr(local, NETID_UNSET)[0];
824    }
825
826    /**
827     * Perform class load-time initializations.
828     */
829    private static native void init();
830
831
832    /*
833     * Returns the InetAddress representing anyLocalAddress
834     * (typically 0.0.0.0 or ::0)
835     */
836    static InetAddress anyLocalAddress() {
837        return impl.anyLocalAddress();
838    }
839
840    private void readObjectNoData (ObjectInputStream s) throws
841                         IOException, ClassNotFoundException {
842        // Android-changed : Don't use null to mean the boot classloader.
843        if (getClass().getClassLoader() != BOOT_CLASSLOADER) {
844            throw new SecurityException ("invalid address type");
845        }
846    }
847
848    // Android-changed : Don't use null to mean the boot classloader.
849    private static final ClassLoader BOOT_CLASSLOADER = Object.class.getClassLoader();
850
851    private void readObject (ObjectInputStream s) throws
852                         IOException, ClassNotFoundException {
853        // Android-changed : Don't use null to mean the boot classloader.
854        if (getClass().getClassLoader() != BOOT_CLASSLOADER) {
855            throw new SecurityException ("invalid address type");
856        }
857        GetField gf = s.readFields();
858        String host = (String)gf.get("hostName", null);
859        int address= gf.get("address", 0);
860        int family= gf.get("family", 0);
861        holder = new InetAddressHolder(host, address, family);
862    }
863
864    /* needed because the serializable fields no longer exist */
865
866    /**
867     * @serialField hostName String
868     * @serialField address int
869     * @serialField family int
870     */
871    private static final ObjectStreamField[] serialPersistentFields = {
872        new ObjectStreamField("hostName", String.class),
873        new ObjectStreamField("address", int.class),
874        new ObjectStreamField("family", int.class),
875    };
876
877    private void writeObject (ObjectOutputStream s) throws
878                        IOException {
879        // Android-changed : Don't use null to mean the boot classloader.
880        if (getClass().getClassLoader() != BOOT_CLASSLOADER) {
881            throw new SecurityException ("invalid address type");
882        }
883        PutField pf = s.putFields();
884        pf.put("hostName", holder().hostName);
885        pf.put("address", holder().address);
886        pf.put("family", holder().family);
887        s.writeFields();
888        s.flush();
889    }
890
891    static final int NETID_UNSET = 0;
892
893    /**
894     * Returns true if the string is a valid numeric IPv4 or IPv6 address (such as "192.168.0.1").
895     * This copes with all forms of address that Java supports, detailed in the {@link InetAddress}
896     * class documentation.
897     *
898     * @hide used by frameworks/base to ensure that a getAllByName won't cause a DNS lookup.
899     */
900    public static boolean isNumeric(String address) {
901        InetAddress inetAddress = parseNumericAddressNoThrow(address);
902        return inetAddress != null && disallowDeprecatedFormats(address, inetAddress) != null;
903    }
904
905    static InetAddress parseNumericAddressNoThrow(String address) {
906        // Accept IPv6 addresses (only) in square brackets for compatibility.
907        if (address.startsWith("[") && address.endsWith("]") && address.indexOf(':') != -1) {
908            address = address.substring(1, address.length() - 1);
909        }
910        StructAddrinfo hints = new StructAddrinfo();
911        hints.ai_flags = AI_NUMERICHOST;
912        InetAddress[] addresses = null;
913        try {
914            addresses = Libcore.os.android_getaddrinfo(address, hints, NETID_UNSET);
915        } catch (GaiException ignored) {
916        }
917        return (addresses != null) ? addresses[0] : null;
918    }
919
920    static InetAddress disallowDeprecatedFormats(String address, InetAddress inetAddress) {
921        // Only IPv4 addresses are problematic.
922        if (!(inetAddress instanceof Inet4Address) || address.indexOf(':') != -1) {
923            return inetAddress;
924        }
925        // If inet_pton(3) can't parse it, it must have been a deprecated format.
926        // We need to return inet_pton(3)'s result to ensure that numbers assumed to be octal
927        // by getaddrinfo(3) are reinterpreted by inet_pton(3) as decimal.
928        return Libcore.os.inet_pton(AF_INET, address);
929    }
930
931    /**
932     * Returns an InetAddress corresponding to the given numeric address (such
933     * as {@code "192.168.0.1"} or {@code "2001:4860:800d::68"}).
934     * This method will never do a DNS lookup. Non-numeric addresses are errors.
935     *
936     * @hide used by frameworks/base's NetworkUtils.numericToInetAddress
937     * @throws IllegalArgumentException if {@code numericAddress} is not a numeric address
938     */
939    public static InetAddress parseNumericAddress(String numericAddress) {
940        if (numericAddress == null || numericAddress.isEmpty()) {
941            return Inet6Address.LOOPBACK;
942        }
943        InetAddress result = parseNumericAddressNoThrow(numericAddress);
944        result = disallowDeprecatedFormats(numericAddress, result);
945        if (result == null) {
946            throw new IllegalArgumentException("Not a numeric address: " + numericAddress);
947        }
948        return result;
949    }
950
951    /**
952     * Removes all entries from the VM's DNS cache. This does not affect the C library's DNS
953     * cache, nor any caching DNS servers between you and the canonical server.
954     * @hide
955     */
956    public static void clearDnsCache() {
957        impl.clearAddressCache();
958    }
959
960    /**
961     * Operates identically to {@code getByName} except host resolution is
962     * performed on the network designated by {@code netId}.
963     *
964     * @param host
965     *            the hostName to be resolved to an address or {@code null}.
966     * @param netId the network to use for host resolution.
967     * @return the {@code InetAddress} instance representing the host.
968     * @throws UnknownHostException if the address lookup fails.
969     * @hide internal use only
970     */
971    public static InetAddress getByNameOnNet(String host, int netId) throws UnknownHostException {
972        return impl.lookupAllHostAddr(host, netId)[0];
973    }
974
975    /**
976     * Operates identically to {@code getAllByName} except host resolution is
977     * performed on the network designated by {@code netId}.
978     *
979     * @param host the hostname or literal IP string to be resolved.
980     * @param netId the network to use for host resolution.
981     * @return the array of addresses associated with the specified host.
982     * @throws UnknownHostException if the address lookup fails.
983     * @hide internal use only
984     */
985    public static InetAddress[] getAllByNameOnNet(String host, int netId) throws UnknownHostException {
986        return impl.lookupAllHostAddr(host, netId).clone();
987    }
988
989    // Only called by java.net.SocketPermission.
990    static InetAddress[] getAllByName0(String authHost, boolean check) throws UnknownHostException {
991        throw new UnsupportedOperationException();
992    }
993
994    // Only called by java.net.SocketPermission.
995    String getHostName(boolean check) {
996        throw new UnsupportedOperationException();
997    }
998}
999