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