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