1 /* 2 * Copyright (C) 2014 The Android Open Source Project 3 * Copyright (c) 1995, 2015, 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 27 package java.net; 28 29 import java.io.ObjectStreamException; 30 import java.io.ObjectStreamField; 31 import java.io.IOException; 32 import java.io.ObjectInputStream; 33 import java.io.ObjectInputStream.GetField; 34 import java.io.ObjectOutputStream; 35 import java.io.ObjectOutputStream.PutField; 36 import sun.net.util.IPAddressUtil; 37 import sun.net.spi.nameservice.*; 38 import android.system.GaiException; 39 import android.system.StructAddrinfo; 40 import libcore.io.Libcore; 41 import 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 790: 50 * Assigned Numbers</i></a>, <a 51 * href="http://www.ietf.org/rfc/rfc1918.txt"> <i>RFC 1918: 52 * Address Allocation for Private Internets</i></a>, <a 53 * href="http://www.ietf.org/rfc/rfc2365.txt"><i>RFC 2365: 54 * Administratively Scoped IP Multicast</i></a>, and <a 55 * href="http://www.ietf.org/rfc/rfc2373.txt"><i>RFC 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 * <h3> Address types </h3> 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 * <dt><b>networkaddress.cache.negative.ttl</b> (default: 10)</dt> 163 * <dd>Indicates the caching policy for un-successful name lookups 164 * from the name service. The value is specified as as integer to 165 * indicate the number of seconds to cache the failure for 166 * un-successful lookups. 167 * <p> 168 * A value of 0 indicates "never cache". 169 * A value of -1 indicates "cache forever". 170 * </dd> 171 * </dl> 172 * </blockquote> 173 * 174 * @author Chris Warth 175 * @see java.net.InetAddress#getByAddress(byte[]) 176 * @see java.net.InetAddress#getByAddress(java.lang.String, byte[]) 177 * @see java.net.InetAddress#getAllByName(java.lang.String) 178 * @see java.net.InetAddress#getByName(java.lang.String) 179 * @see java.net.InetAddress#getLocalHost() 180 * @since JDK1.0 181 */ 182 public 183 class InetAddress implements java.io.Serializable { 184 185 static class InetAddressHolder { 186 /** 187 * Reserve the original application specified hostname. 188 * 189 * The original hostname is useful for domain-based endpoint 190 * identification (see RFC 2818 and RFC 6125). If an address 191 * was created with a raw IP address, a reverse name lookup 192 * may introduce endpoint identification security issue via 193 * DNS forging. 194 * 195 * Oracle JSSE provider is using this original hostname, via 196 * sun.misc.JavaNetAccess, for SSL/TLS endpoint identification. 197 * 198 * Note: May define a new public method in the future if necessary. 199 */ 200 private String originalHostName; 201 InetAddressHolder()202 InetAddressHolder() {} 203 InetAddressHolder(String hostName, int address, int family)204 InetAddressHolder(String hostName, int address, int family) { 205 this.originalHostName = hostName; 206 this.hostName = hostName; 207 this.address = address; 208 this.family = family; 209 } 210 init(String hostName, int family)211 void init(String hostName, int family) { 212 this.originalHostName = hostName; 213 this.hostName = hostName; 214 if (family != -1) { 215 this.family = family; 216 } 217 } 218 219 String hostName; 220 getHostName()221 String getHostName() { 222 return hostName; 223 } 224 getOriginalHostName()225 String getOriginalHostName() { 226 return originalHostName; 227 } 228 229 /** 230 * Holds a 32-bit IPv4 address. 231 */ 232 int address; 233 getAddress()234 int getAddress() { 235 return address; 236 } 237 238 /** 239 * Specifies the address family type, for instance, AF_INET for IPv4 240 * addresses, and AF_INET6 for IPv6 addresses. 241 */ 242 int family; 243 getFamily()244 int getFamily() { 245 return family; 246 } 247 } 248 249 transient InetAddressHolder holder; 250 holder()251 InetAddressHolder holder() { 252 return holder; 253 } 254 255 /* The implementation is always dual stack IPv6/IPv4 on android */ 256 static final InetAddressImpl impl = new Inet6AddressImpl(); 257 258 /* Used to store the name service provider */ 259 private static final NameService nameService = new NameService() { 260 public InetAddress[] lookupAllHostAddr(String host, int netId) 261 throws UnknownHostException { 262 return impl.lookupAllHostAddr(host, netId); 263 } 264 public String getHostByAddr(byte[] addr) 265 throws UnknownHostException { 266 return impl.getHostByAddr(addr); 267 } 268 }; 269 270 /* Used to store the best available hostname */ 271 private transient String canonicalHostName = null; 272 273 /** use serialVersionUID from JDK 1.0.2 for interoperability */ 274 private static final long serialVersionUID = 3286316764910316507L; 275 276 /** 277 * Constructor for the Socket.accept() method. 278 * This creates an empty InetAddress, which is filled in by 279 * the accept() method. This InetAddress, however, is not 280 * put in the address cache, since it is not created by name. 281 */ InetAddress()282 InetAddress() { 283 holder = new InetAddressHolder(); 284 } 285 286 /** 287 * Replaces the de-serialized object with an Inet4Address object. 288 * 289 * @return the alternate object to the de-serialized object. 290 * 291 * @throws ObjectStreamException if a new object replacing this 292 * object could not be created 293 */ readResolve()294 private Object readResolve() throws ObjectStreamException { 295 // will replace the deserialized 'this' object 296 return new Inet4Address(holder().getHostName(), holder().getAddress()); 297 } 298 299 /** 300 * Utility routine to check if the InetAddress is an 301 * IP multicast address. 302 * @return a {@code boolean} indicating if the InetAddress is 303 * an IP multicast address 304 * @since JDK1.1 305 */ isMulticastAddress()306 public boolean isMulticastAddress() { 307 return false; 308 } 309 310 /** 311 * Utility routine to check if the InetAddress in a wildcard address. 312 * @return a {@code boolean} indicating if the Inetaddress is 313 * a wildcard address. 314 * @since 1.4 315 */ isAnyLocalAddress()316 public boolean isAnyLocalAddress() { 317 return false; 318 } 319 320 /** 321 * Utility routine to check if the InetAddress is a loopback address. 322 * 323 * @return a {@code boolean} indicating if the InetAddress is 324 * a loopback address; or false otherwise. 325 * @since 1.4 326 */ isLoopbackAddress()327 public boolean isLoopbackAddress() { 328 return false; 329 } 330 331 /** 332 * Utility routine to check if the InetAddress is an link local address. 333 * 334 * @return a {@code boolean} indicating if the InetAddress is 335 * a link local address; or false if address is not a link local unicast address. 336 * @since 1.4 337 */ isLinkLocalAddress()338 public boolean isLinkLocalAddress() { 339 return false; 340 } 341 342 /** 343 * Utility routine to check if the InetAddress is a site local address. 344 * 345 * @return a {@code boolean} indicating if the InetAddress is 346 * a site local address; or false if address is not a site local unicast address. 347 * @since 1.4 348 */ isSiteLocalAddress()349 public boolean isSiteLocalAddress() { 350 return false; 351 } 352 353 /** 354 * Utility routine to check if the multicast address has global scope. 355 * 356 * @return a {@code boolean} indicating if the address has 357 * is a multicast address of global scope, false if it is not 358 * of global scope or it is not a multicast address 359 * @since 1.4 360 */ isMCGlobal()361 public boolean isMCGlobal() { 362 return false; 363 } 364 365 /** 366 * Utility routine to check if the multicast address has node scope. 367 * 368 * @return a {@code boolean} indicating if the address has 369 * is a multicast address of node-local scope, false if it is not 370 * of node-local scope or it is not a multicast address 371 * @since 1.4 372 */ isMCNodeLocal()373 public boolean isMCNodeLocal() { 374 return false; 375 } 376 377 /** 378 * Utility routine to check if the multicast address has link scope. 379 * 380 * @return a {@code boolean} indicating if the address has 381 * is a multicast address of link-local scope, false if it is not 382 * of link-local scope or it is not a multicast address 383 * @since 1.4 384 */ isMCLinkLocal()385 public boolean isMCLinkLocal() { 386 return false; 387 } 388 389 /** 390 * Utility routine to check if the multicast address has site scope. 391 * 392 * @return a {@code boolean} indicating if the address has 393 * is a multicast address of site-local scope, false if it is not 394 * of site-local scope or it is not a multicast address 395 * @since 1.4 396 */ isMCSiteLocal()397 public boolean isMCSiteLocal() { 398 return false; 399 } 400 401 /** 402 * Utility routine to check if the multicast address has organization scope. 403 * 404 * @return a {@code boolean} indicating if the address has 405 * is a multicast address of organization-local scope, 406 * false if it is not of organization-local scope 407 * or it is not a multicast address 408 * @since 1.4 409 */ isMCOrgLocal()410 public boolean isMCOrgLocal() { 411 return false; 412 } 413 414 415 /** 416 * Test whether that address is reachable. Best effort is made by the 417 * implementation to try to reach the host, but firewalls and server 418 * configuration may block requests resulting in a unreachable status 419 * while some specific ports may be accessible. 420 * A typical implementation will use ICMP ECHO REQUESTs if the 421 * privilege can be obtained, otherwise it will try to establish 422 * a TCP connection on port 7 (Echo) of the destination host. 423 * <p> 424 * The timeout value, in milliseconds, indicates the maximum amount of time 425 * the try should take. If the operation times out before getting an 426 * answer, the host is deemed unreachable. A negative value will result 427 * in an IllegalArgumentException being thrown. 428 * 429 * @param timeout the time, in milliseconds, before the call aborts 430 * @return a {@code boolean} indicating if the address is reachable. 431 * @throws IOException if a network error occurs 432 * @throws IllegalArgumentException if {@code timeout} is negative. 433 * @since 1.5 434 */ isReachable(int timeout)435 public boolean isReachable(int timeout) throws IOException { 436 return isReachable(null, 0, timeout); 437 } 438 439 /** 440 * Test whether that address is reachable. Best effort is made by the 441 * implementation to try to reach the host, but firewalls and server 442 * configuration may block requests resulting in a unreachable status 443 * while some specific ports may be accessible. 444 * <p> 445 * Android implementation attempts ICMP ECHO REQUESTs first, on failure it 446 * will fall back to TCP ECHO REQUESTs. Success on either protocol will 447 * return true. 448 * <p> 449 * The {@code network interface} and {@code ttl} parameters 450 * let the caller specify which network interface the test will go through 451 * and the maximum number of hops the packets should go through. 452 * A negative value for the {@code ttl} will result in an 453 * IllegalArgumentException being thrown. 454 * <p> 455 * The timeout value, in milliseconds, indicates the maximum amount of time 456 * the try should take. If the operation times out before getting an 457 * answer, the host is deemed unreachable. A negative value will result 458 * in an IllegalArgumentException being thrown. 459 * 460 * @param netif the NetworkInterface through which the 461 * test will be done, or null for any interface 462 * @param ttl the maximum numbers of hops to try or 0 for the 463 * default 464 * @param timeout the time, in milliseconds, before the call aborts 465 * @throws IllegalArgumentException if either {@code timeout} 466 * or {@code ttl} are negative. 467 * @return a {@code boolean}indicating if the address is reachable. 468 * @throws IOException if a network error occurs 469 * @since 1.5 470 */ isReachable(NetworkInterface netif, int ttl, int timeout)471 public boolean isReachable(NetworkInterface netif, int ttl, 472 int timeout) throws IOException { 473 if (ttl < 0) 474 throw new IllegalArgumentException("ttl can't be negative"); 475 if (timeout < 0) 476 throw new IllegalArgumentException("timeout can't be negative"); 477 478 return impl.isReachable(this, timeout, netif, ttl); 479 } 480 481 /** 482 * @hide For testing only 483 */ isReachableByICMP(int timeout)484 public boolean isReachableByICMP(int timeout) throws IOException { 485 return ((Inet6AddressImpl) impl).icmpEcho(this, timeout, null, 0); 486 } 487 488 /** 489 * Gets the host name for this IP address. 490 * 491 * <p>If this InetAddress was created with a host name, 492 * this host name will be remembered and returned; 493 * otherwise, a reverse name lookup will be performed 494 * and the result will be returned based on the system 495 * configured name lookup service. If a lookup of the name service 496 * is required, call 497 * {@link #getCanonicalHostName() getCanonicalHostName}. 498 * 499 * <p>If there is a security manager, its 500 * {@code checkConnect} method is first called 501 * with the hostname and {@code -1} 502 * as its arguments to see if the operation is allowed. 503 * If the operation is not allowed, it will return 504 * the textual representation of the IP address. 505 * 506 * @return the host name for this IP address, or if the operation 507 * is not allowed by the security check, the textual 508 * representation of the IP address. 509 * 510 * @see InetAddress#getCanonicalHostName 511 * @see SecurityManager#checkConnect 512 */ getHostName()513 public String getHostName() { 514 if (holder().getHostName() == null) { 515 holder().hostName = InetAddress.getHostFromNameService(this); 516 } 517 return holder().getHostName(); 518 } 519 520 /** 521 * Gets the fully qualified domain name for this IP address. 522 * Best effort method, meaning we may not be able to return 523 * the FQDN depending on the underlying system configuration. 524 * 525 * <p>If there is a security manager, this method first 526 * calls its {@code checkConnect} method 527 * with the hostname and {@code -1} 528 * as its arguments to see if the calling code is allowed to know 529 * the hostname for this IP address, i.e., to connect to the host. 530 * If the operation is not allowed, it will return 531 * the textual representation of the IP address. 532 * 533 * @return the fully qualified domain name for this IP address, 534 * or if the operation is not allowed by the security check, 535 * the textual representation of the IP address. 536 * 537 * @see SecurityManager#checkConnect 538 * 539 * @since 1.4 540 */ getCanonicalHostName()541 public String getCanonicalHostName() { 542 if (canonicalHostName == null) { 543 canonicalHostName = InetAddress.getHostFromNameService(this); 544 } 545 return canonicalHostName; 546 } 547 548 /** 549 * Returns the hostname for this address. 550 * 551 * <p>If there is a security manager, this method first 552 * calls its {@code checkConnect} method 553 * with the hostname and {@code -1} 554 * as its arguments to see if the calling code is allowed to know 555 * the hostname for this IP address, i.e., to connect to the host. 556 * If the operation is not allowed, it will return 557 * the textual representation of the IP address. 558 * 559 * @return the host name for this IP address, or if the operation 560 * is not allowed by the security check, the textual 561 * representation of the IP address. 562 * 563 * @see SecurityManager#checkConnect 564 */ getHostFromNameService(InetAddress addr)565 private static String getHostFromNameService(InetAddress addr) { 566 String host = null; 567 try { 568 // first lookup the hostname 569 host = nameService.getHostByAddr(addr.getAddress()); 570 571 /* now get all the IP addresses for this hostname, 572 * and make sure one of them matches the original IP 573 * address. We do this to try and prevent spoofing. 574 */ 575 InetAddress[] arr = nameService.lookupAllHostAddr(host, NETID_UNSET); 576 boolean ok = false; 577 578 if (arr != null) { 579 for(int i = 0; !ok && i < arr.length; i++) { 580 ok = addr.equals(arr[i]); 581 } 582 } 583 584 //XXX: if it looks a spoof just return the address? 585 if (!ok) { 586 host = addr.getHostAddress(); 587 return host; 588 } 589 } catch (UnknownHostException e) { 590 host = addr.getHostAddress(); 591 } 592 593 return host; 594 } 595 596 /** 597 * Returns the raw IP address of this {@code InetAddress} 598 * object. The result is in network byte order: the highest order 599 * byte of the address is in {@code getAddress()[0]}. 600 * 601 * @return the raw IP address of this object. 602 */ getAddress()603 public byte[] getAddress() { 604 return null; 605 } 606 607 /** 608 * Returns the IP address string in textual presentation. 609 * 610 * @return the raw IP address in a string format. 611 * @since JDK1.0.2 612 */ getHostAddress()613 public String getHostAddress() { 614 return null; 615 } 616 617 /** 618 * Returns a hashcode for this IP address. 619 * 620 * @return a hash code value for this IP address. 621 */ hashCode()622 public int hashCode() { 623 return -1; 624 } 625 626 /** 627 * Compares this object against the specified object. 628 * The result is {@code true} if and only if the argument is 629 * not {@code null} and it represents the same IP address as 630 * this object. 631 * <p> 632 * Two instances of {@code InetAddress} represent the same IP 633 * address if the length of the byte arrays returned by 634 * {@code getAddress} is the same for both, and each of the 635 * array components is the same for the byte arrays. 636 * 637 * @param obj the object to compare against. 638 * @return {@code true} if the objects are the same; 639 * {@code false} otherwise. 640 * @see java.net.InetAddress#getAddress() 641 */ equals(Object obj)642 public boolean equals(Object obj) { 643 return false; 644 } 645 646 /** 647 * Converts this IP address to a {@code String}. The 648 * string returned is of the form: hostname / literal IP 649 * address. 650 * 651 * If the host name is unresolved, no reverse name service lookup 652 * is performed. The hostname part will be represented by an empty string. 653 * 654 * @return a string representation of this IP address. 655 */ toString()656 public String toString() { 657 String hostName = holder().getHostName(); 658 return ((hostName != null) ? hostName : "") 659 + "/" + getHostAddress(); 660 } 661 662 /** 663 * Creates an InetAddress based on the provided host name and IP address. 664 * No name service is checked for the validity of the address. 665 * 666 * <p> The host name can either be a machine name, such as 667 * "{@code java.sun.com}", or a textual representation of its IP 668 * address. 669 * <p> No validity checking is done on the host name either. 670 * 671 * <p> If addr specifies an IPv4 address an instance of Inet4Address 672 * will be returned; otherwise, an instance of Inet6Address 673 * will be returned. 674 * 675 * <p> IPv4 address byte array must be 4 bytes long and IPv6 byte array 676 * must be 16 bytes long 677 * 678 * @param host the specified host 679 * @param addr the raw IP address in network byte order 680 * @return an InetAddress object created from the raw IP address. 681 * @exception UnknownHostException if IP address is of illegal length 682 * @since 1.4 683 */ getByAddress(String host, byte[] addr)684 public static InetAddress getByAddress(String host, byte[] addr) throws UnknownHostException { 685 return getByAddress(host, addr, -1 /* scopeId */); 686 } 687 688 // Do not delete. Called from native code. getByAddress(String host, byte[] addr, int scopeId)689 private static InetAddress getByAddress(String host, byte[] addr, int scopeId) 690 throws UnknownHostException { 691 if (host != null && host.length() > 0 && host.charAt(0) == '[') { 692 if (host.charAt(host.length()-1) == ']') { 693 host = host.substring(1, host.length() -1); 694 } 695 } 696 if (addr != null) { 697 if (addr.length == Inet4Address.INADDRSZ) { 698 return new Inet4Address(host, addr); 699 } else if (addr.length == Inet6Address.INADDRSZ) { 700 byte[] newAddr 701 = IPAddressUtil.convertFromIPv4MappedAddress(addr); 702 if (newAddr != null) { 703 return new Inet4Address(host, newAddr); 704 } else { 705 return new Inet6Address(host, addr, scopeId); 706 } 707 } 708 } 709 throw new UnknownHostException("addr is of illegal length"); 710 } 711 712 713 /** 714 * Determines the IP address of a host, given the host's name. 715 * 716 * <p> The host name can either be a machine name, such as 717 * "{@code java.sun.com}", or a textual representation of its 718 * IP address. If a literal IP address is supplied, only the 719 * validity of the address format is checked. 720 * 721 * <p> For {@code host} specified in literal IPv6 address, 722 * either the form defined in RFC 2732 or the literal IPv6 address 723 * format defined in RFC 2373 is accepted. IPv6 scoped addresses are also 724 * supported. See <a href="Inet6Address.html#scoped">here</a> for a description of IPv6 725 * scoped addresses. 726 * 727 * <p> If the host is {@code null} then an {@code InetAddress} 728 * representing an address of the loopback interface is returned. 729 * See <a href="http://www.ietf.org/rfc/rfc3330.txt">RFC 3330</a> 730 * section 2 and <a href="http://www.ietf.org/rfc/rfc2373.txt">RFC 2373</a> 731 * section 2.5.3. </p> 732 * 733 * @param host the specified host, or {@code null}. 734 * @return an IP address for the given host name. 735 * @exception UnknownHostException if no IP address for the 736 * {@code host} could be found, or if a scope_id was specified 737 * for a global IPv6 address. 738 * @exception SecurityException if a security manager exists 739 * and its checkConnect method doesn't allow the operation 740 */ getByName(String host)741 public static InetAddress getByName(String host) 742 throws UnknownHostException { 743 return impl.lookupAllHostAddr(host, NETID_UNSET)[0]; 744 } 745 746 /** 747 * Given the name of a host, returns an array of its IP addresses, 748 * based on the configured name service on the system. 749 * 750 * <p> The host name can either be a machine name, such as 751 * "{@code java.sun.com}", or a textual representation of its IP 752 * address. If a literal IP address is supplied, only the 753 * validity of the address format is checked. 754 * 755 * <p> For {@code host} specified in <i>literal IPv6 address</i>, 756 * either the form defined in RFC 2732 or the literal IPv6 address 757 * format defined in RFC 2373 is accepted. A literal IPv6 address may 758 * also be qualified by appending a scoped zone identifier or scope_id. 759 * The syntax and usage of scope_ids is described 760 * <a href="Inet6Address.html#scoped">here</a>. 761 * <p> If the host is {@code null} then an {@code InetAddress} 762 * representing an address of the loopback interface is returned. 763 * See <a href="http://www.ietf.org/rfc/rfc3330.txt">RFC 3330</a> 764 * section 2 and <a href="http://www.ietf.org/rfc/rfc2373.txt">RFC 2373</a> 765 * section 2.5.3. </p> 766 * 767 * <p> If there is a security manager and {@code host} is not 768 * null and {@code host.length() } is not equal to zero, the 769 * security manager's 770 * {@code checkConnect} method is called 771 * with the hostname and {@code -1} 772 * as its arguments to see if the operation is allowed. 773 * 774 * @param host the name of the host, or {@code null}. 775 * @return an array of all the IP addresses for a given host name. 776 * 777 * @exception UnknownHostException if no IP address for the 778 * {@code host} could be found, or if a scope_id was specified 779 * for a global IPv6 address. 780 * @exception SecurityException if a security manager exists and its 781 * {@code checkConnect} method doesn't allow the operation. 782 * 783 * @see SecurityManager#checkConnect 784 */ getAllByName(String host)785 public static InetAddress[] getAllByName(String host) 786 throws UnknownHostException { 787 return impl.lookupAllHostAddr(host, NETID_UNSET).clone(); 788 } 789 790 /** 791 * Returns the loopback address. 792 * <p> 793 * The InetAddress returned will represent the IPv4 794 * loopback address, 127.0.0.1, or the IPv6 loopback 795 * address, ::1. The IPv4 loopback address returned 796 * is only one of many in the form 127.*.*.* 797 * 798 * @return the InetAddress loopback instance. 799 * @since 1.7 800 */ getLoopbackAddress()801 public static InetAddress getLoopbackAddress() { 802 return impl.loopbackAddresses()[0]; 803 } 804 805 /** 806 * Returns an {@code InetAddress} object given the raw IP address . 807 * The argument is in network byte order: the highest order 808 * byte of the address is in {@code getAddress()[0]}. 809 * 810 * <p> This method doesn't block, i.e. no reverse name service lookup 811 * is performed. 812 * 813 * <p> IPv4 address byte array must be 4 bytes long and IPv6 byte array 814 * must be 16 bytes long 815 * 816 * @param addr the raw IP address in network byte order 817 * @return an InetAddress object created from the raw IP address. 818 * @exception UnknownHostException if IP address is of illegal length 819 * @since 1.4 820 */ getByAddress(byte[] addr)821 public static InetAddress getByAddress(byte[] addr) 822 throws UnknownHostException { 823 return getByAddress(null, addr); 824 } 825 826 /** 827 * Returns the address of the local host. This is achieved by retrieving 828 * the name of the host from the system, then resolving that name into 829 * an {@code InetAddress}. 830 * 831 * <P>Note: The resolved address may be cached for a short period of time. 832 * </P> 833 * 834 * <p>If there is a security manager, its 835 * {@code checkConnect} method is called 836 * with the local host name and {@code -1} 837 * as its arguments to see if the operation is allowed. 838 * If the operation is not allowed, an InetAddress representing 839 * the loopback address is returned. 840 * 841 * @return the address of the local host. 842 * 843 * @exception UnknownHostException if the local host name could not 844 * be resolved into an address. 845 * 846 * @see SecurityManager#checkConnect 847 * @see java.net.InetAddress#getByName(java.lang.String) 848 */ getLocalHost()849 public static InetAddress getLocalHost() throws UnknownHostException { 850 String local = Libcore.os.uname().nodename; 851 return impl.lookupAllHostAddr(local, NETID_UNSET)[0]; 852 } 853 854 /* 855 * Returns the InetAddress representing anyLocalAddress 856 * (typically 0.0.0.0 or ::0) 857 */ anyLocalAddress()858 static InetAddress anyLocalAddress() { 859 return impl.anyLocalAddress(); 860 } 861 readObjectNoData(ObjectInputStream s)862 private void readObjectNoData (ObjectInputStream s) throws 863 IOException, ClassNotFoundException { 864 // Android-changed: Don't use null to mean the boot classloader. 865 if (getClass().getClassLoader() != BOOT_CLASSLOADER) { 866 throw new SecurityException ("invalid address type"); 867 } 868 } 869 870 // Android-changed: Don't use null to mean the boot classloader. 871 private static final ClassLoader BOOT_CLASSLOADER = Object.class.getClassLoader(); 872 readObject(ObjectInputStream s)873 private void readObject (ObjectInputStream s) throws 874 IOException, ClassNotFoundException { 875 // Android-changed: Don't use null to mean the boot classloader. 876 if (getClass().getClassLoader() != BOOT_CLASSLOADER) { 877 throw new SecurityException ("invalid address type"); 878 } 879 GetField gf = s.readFields(); 880 String host = (String)gf.get("hostName", null); 881 int address= gf.get("address", 0); 882 int family= gf.get("family", 0); 883 holder = new InetAddressHolder(host, address, family); 884 } 885 886 /* needed because the serializable fields no longer exist */ 887 888 /** 889 * @serialField hostName String 890 * @serialField address int 891 * @serialField family int 892 */ 893 private static final ObjectStreamField[] serialPersistentFields = { 894 new ObjectStreamField("hostName", String.class), 895 new ObjectStreamField("address", int.class), 896 new ObjectStreamField("family", int.class), 897 }; 898 writeObject(ObjectOutputStream s)899 private void writeObject (ObjectOutputStream s) throws 900 IOException { 901 // Android-changed: Don't use null to mean the boot classloader. 902 if (getClass().getClassLoader() != BOOT_CLASSLOADER) { 903 throw new SecurityException ("invalid address type"); 904 } 905 PutField pf = s.putFields(); 906 pf.put("hostName", holder().hostName); 907 pf.put("address", holder().address); 908 pf.put("family", holder().family); 909 s.writeFields(); 910 s.flush(); 911 } 912 913 static final int NETID_UNSET = 0; 914 915 /** 916 * Returns true if the string is a valid numeric IPv4 or IPv6 address (such as "192.168.0.1"). 917 * This copes with all forms of address that Java supports, detailed in the {@link InetAddress} 918 * class documentation. 919 * 920 * @hide used by frameworks/base to ensure that a getAllByName won't cause a DNS lookup. 921 */ isNumeric(String address)922 public static boolean isNumeric(String address) { 923 InetAddress inetAddress = parseNumericAddressNoThrow(address); 924 return inetAddress != null && disallowDeprecatedFormats(address, inetAddress) != null; 925 } 926 parseNumericAddressNoThrow(String address)927 static InetAddress parseNumericAddressNoThrow(String address) { 928 // Accept IPv6 addresses (only) in square brackets for compatibility. 929 if (address.startsWith("[") && address.endsWith("]") && address.indexOf(':') != -1) { 930 address = address.substring(1, address.length() - 1); 931 } 932 StructAddrinfo hints = new StructAddrinfo(); 933 hints.ai_flags = AI_NUMERICHOST; 934 InetAddress[] addresses = null; 935 try { 936 addresses = Libcore.os.android_getaddrinfo(address, hints, NETID_UNSET); 937 } catch (GaiException ignored) { 938 } 939 return (addresses != null) ? addresses[0] : null; 940 } 941 disallowDeprecatedFormats(String address, InetAddress inetAddress)942 static InetAddress disallowDeprecatedFormats(String address, InetAddress inetAddress) { 943 // Only IPv4 addresses are problematic. 944 if (!(inetAddress instanceof Inet4Address) || address.indexOf(':') != -1) { 945 return inetAddress; 946 } 947 // If inet_pton(3) can't parse it, it must have been a deprecated format. 948 // We need to return inet_pton(3)'s result to ensure that numbers assumed to be octal 949 // by getaddrinfo(3) are reinterpreted by inet_pton(3) as decimal. 950 return Libcore.os.inet_pton(AF_INET, address); 951 } 952 953 /** 954 * Returns an InetAddress corresponding to the given numeric address (such 955 * as {@code "192.168.0.1"} or {@code "2001:4860:800d::68"}). 956 * This method will never do a DNS lookup. Non-numeric addresses are errors. 957 * 958 * @hide used by frameworks/base's NetworkUtils.numericToInetAddress 959 * @throws IllegalArgumentException if {@code numericAddress} is not a numeric address 960 */ parseNumericAddress(String numericAddress)961 public static InetAddress parseNumericAddress(String numericAddress) { 962 if (numericAddress == null || numericAddress.isEmpty()) { 963 return Inet6Address.LOOPBACK; 964 } 965 InetAddress result = parseNumericAddressNoThrow(numericAddress); 966 result = disallowDeprecatedFormats(numericAddress, result); 967 if (result == null) { 968 throw new IllegalArgumentException("Not a numeric address: " + numericAddress); 969 } 970 return result; 971 } 972 973 /** 974 * Removes all entries from the VM's DNS cache. This does not affect the C library's DNS 975 * cache, nor any caching DNS servers between you and the canonical server. 976 * @hide 977 */ clearDnsCache()978 public static void clearDnsCache() { 979 impl.clearAddressCache(); 980 } 981 982 /** 983 * Operates identically to {@code getByName} except host resolution is 984 * performed on the network designated by {@code netId}. 985 * 986 * @param host 987 * the hostName to be resolved to an address or {@code null}. 988 * @param netId the network to use for host resolution. 989 * @return the {@code InetAddress} instance representing the host. 990 * @throws UnknownHostException if the address lookup fails. 991 * @hide internal use only 992 */ getByNameOnNet(String host, int netId)993 public static InetAddress getByNameOnNet(String host, int netId) throws UnknownHostException { 994 return impl.lookupAllHostAddr(host, netId)[0]; 995 } 996 997 /** 998 * Operates identically to {@code getAllByName} except host resolution is 999 * performed on the network designated by {@code netId}. 1000 * 1001 * @param host the hostname or literal IP string to be resolved. 1002 * @param netId the network to use for host resolution. 1003 * @return the array of addresses associated with the specified host. 1004 * @throws UnknownHostException if the address lookup fails. 1005 * @hide internal use only 1006 */ getAllByNameOnNet(String host, int netId)1007 public static InetAddress[] getAllByNameOnNet(String host, int netId) throws UnknownHostException { 1008 return impl.lookupAllHostAddr(host, netId).clone(); 1009 } 1010 1011 // Only called by java.net.SocketPermission. getAllByName0(String authHost, boolean check)1012 static InetAddress[] getAllByName0(String authHost, boolean check) throws UnknownHostException { 1013 throw new UnsupportedOperationException(); 1014 } 1015 1016 // Only called by java.net.SocketPermission. getHostName(boolean check)1017 String getHostName(boolean check) { 1018 throw new UnsupportedOperationException(); 1019 } 1020 } 1021