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