InetAddress.java revision b46dab348e2007bc08abaf7ecae34d89a2474e50
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.security.AccessController; 30import java.util.Arrays; 31import java.util.Collections; 32import java.util.Comparator; 33import java.util.Enumeration; 34import java.util.List; 35import org.apache.harmony.luni.platform.OSMemory; 36import org.apache.harmony.luni.platform.Platform; 37import org.apache.harmony.luni.util.PriviAction; 38 39/** 40 * An Internet Protocol (IP) address. This can be either an IPv4 address or an IPv6 address, and 41 * in practice you'll have an instance of either {@code Inet4Address} or {@code Inet6Address} (this 42 * class cannot be instantiated directly). Most code does not need to distinguish between the two 43 * families, and should use {@code InetAddress}. 44 * 45 * <p>An {@code InetAddress} may have a hostname (accessible via {@code getHostName}), but may not, 46 * depending on how the {@code InetAddress} was created. 47 * 48 * <h4>IPv4 numeric address formats</h4> 49 * <p>The {@code getAllByName} method accepts IPv4 addresses in the following forms: 50 * <ul> 51 * <li>{@code "1.2.3.4"} - 1.2.3.4 52 * <li>{@code "1.2.3"} - 1.2.0.3 53 * <li>{@code "1.2"} - 1.0.0.2 54 * <li>{@code "16909060"} - 1.2.3.4 55 * </ul> 56 * <p>In the first three cases, each number is treated as an 8-bit value between 0 and 255. 57 * In the fourth case, the single number is treated as a 32-bit value representing the entire 58 * address. 59 * <p>Note that each numeric part can be expressed in decimal (as above) or hex. For example, 60 * {@code "0x01020304"} is equivalent to 1.2.3.4 and {@code "0xa.0xb.0xc.0xd"} is equivalent 61 * to 10.11.12.13. 62 * 63 * <p>Typically, only the four-dot decimal form ({@code "1.2.3.4"}) is ever used. Any method that 64 * <i>returns</i> a textual numeric address will use four-dot decimal form. 65 * 66 * <h4>IPv6 numeric address formats</h4> 67 * <p>The {@code getAllByName} method accepts IPv6 addresses in the following forms (this text 68 * comes from <a href="http://www.ietf.org/rfc/rfc2373.txt">RFC 2373</a>, which you should consult 69 * for full details of IPv6 addressing): 70 * <ul> 71 * <li><p>The preferred form is {@code x:x:x:x:x:x:x:x}, where the 'x's are the 72 * hexadecimal values of the eight 16-bit pieces of the address. 73 * Note that it is not necessary to write the leading zeros in an 74 * individual field, but there must be at least one numeral in every 75 * field (except for the case described in the next bullet). 76 * Examples: 77 * <pre> 78 * FEDC:BA98:7654:3210:FEDC:BA98:7654:3210 79 * 1080:0:0:0:8:800:200C:417A</pre> 80 * </li> 81 * <li>Due to some methods of allocating certain styles of IPv6 82 * addresses, it will be common for addresses to contain long strings 83 * of zero bits. In order to make writing addresses containing zero 84 * bits easier a special syntax is available to compress the zeros. 85 * The use of "::" indicates multiple groups of 16-bits of zeros. 86 * The "::" can only appear once in an address. The "::" can also be 87 * used to compress the leading and/or trailing zeros in an address. 88 * 89 * For example the following addresses: 90 * <pre> 91 * 1080:0:0:0:8:800:200C:417A a unicast address 92 * FF01:0:0:0:0:0:0:101 a multicast address 93 * 0:0:0:0:0:0:0:1 the loopback address 94 * 0:0:0:0:0:0:0:0 the unspecified addresses</pre> 95 * may be represented as: 96 * <pre> 97 * 1080::8:800:200C:417A a unicast address 98 * FF01::101 a multicast address 99 * ::1 the loopback address 100 * :: the unspecified addresses</pre> 101 * </li> 102 * <li><p>An alternative form that is sometimes more convenient when dealing 103 * with a mixed environment of IPv4 and IPv6 nodes is 104 * {@code x:x:x:x:x:x:d.d.d.d}, where the 'x's are the hexadecimal values of 105 * the six high-order 16-bit pieces of the address, and the 'd's are 106 * the decimal values of the four low-order 8-bit pieces of the 107 * address (standard IPv4 representation). Examples: 108 * <pre> 109 * 0:0:0:0:0:0:13.1.68.3 110 * 0:0:0:0:0:FFFF:129.144.52.38</pre> 111 * or in compressed form: 112 * <pre> 113 * ::13.1.68.3 114 * ::FFFF:129.144.52.38</pre> 115 * </li> 116 * </ul> 117 * <p>Scopes are given using a trailing {@code %} followed by the scope id, as in 118 * {@code 1080::8:800:200C:417A%2} or {@code 1080::8:800:200C:417A%en0}. 119 * See <a href="https://www.ietf.org/rfc/rfc4007.txt">RFC 4007</a> for more on IPv6's scoped 120 * address architecture. 121 * 122 * <p>Additionally, for backwards compatibility, IPv6 addresses may be surrounded by square 123 * brackets. 124 * 125 * <h4>DNS caching</h4> 126 * <p>On Android, addresses are cached for 600 seconds (10 minutes) by default. Failed lookups are 127 * cached for 10 seconds. The underlying C library or OS may cache for longer, but you can control 128 * the Java-level caching with the usual {@code "networkaddress.cache.ttl"} and 129 * {@code "networkaddress.cache.negative.ttl"} system properties. These are parsed as integer 130 * numbers of seconds, where the special value 0 means "don't cache" and -1 means "cache forever". 131 * 132 * <p>Note also that on Android – unlike the RI – the cache is not unbounded. The 133 * current implementation caches around 512 entries, removed on a least-recently-used basis. 134 * (Obviously, you should not rely on these details.) 135 * 136 * @see Inet4Address 137 * @see Inet6Address 138 */ 139public class InetAddress implements Serializable { 140 /** Our Java-side DNS cache. */ 141 private static final AddressCache addressCache = new AddressCache(); 142 143 private static final String ERRMSG_CONNECTION_REFUSED = "Connection refused"; 144 145 private static final long serialVersionUID = 3286316764910316507L; 146 147 String hostName; 148 149 private static class WaitReachable { 150 } 151 152 private transient Object waitReachable = new WaitReachable(); 153 154 private boolean reached; 155 156 private int addrCount; 157 158 int family = 0; 159 160 byte[] ipaddress; 161 162 /** 163 * Constructs an {@code InetAddress}. 164 * 165 * Note: this constructor should not be used. Creating an InetAddress 166 * without specifying whether it's an IPv4 or IPv6 address does not make 167 * sense, because subsequent code cannot know which of of the subclasses' 168 * methods need to be called to implement a given InetAddress method. The 169 * proper way to create an InetAddress is to call new Inet4Address or 170 * Inet6Address or to use one of the static methods that return 171 * InetAddresses (e.g., getByAddress). That is why the API does not have 172 * public constructors for any of these classes. 173 */ 174 InetAddress() {} 175 176 /** 177 * Compares this {@code InetAddress} instance against the specified address 178 * in {@code obj}. Two addresses are equal if their address byte arrays have 179 * the same length and if the bytes in the arrays are equal. 180 * 181 * @param obj 182 * the object to be tested for equality. 183 * @return {@code true} if both objects are equal, {@code false} otherwise. 184 */ 185 @Override 186 public boolean equals(Object obj) { 187 if (!(obj instanceof InetAddress)) { 188 return false; 189 } 190 return Arrays.equals(this.ipaddress, ((InetAddress) obj).ipaddress); 191 } 192 193 /** 194 * Returns the IP address represented by this {@code InetAddress} instance 195 * as a byte array. The elements are in network order (the highest order 196 * address byte is in the zeroth element). 197 * 198 * @return the address in form of a byte array. 199 */ 200 public byte[] getAddress() { 201 return ipaddress.clone(); 202 } 203 204 static final Comparator<byte[]> SHORTEST_FIRST = new Comparator<byte[]>() { 205 public int compare(byte[] a1, byte[] a2) { 206 return a1.length - a2.length; 207 } 208 }; 209 210 /** 211 * Converts an array of byte arrays representing raw IP addresses of a host 212 * to an array of InetAddress objects, sorting to respect the value of the 213 * system property {@code "java.net.preferIPv6Addresses"}. 214 * 215 * @param rawAddresses the raw addresses to convert. 216 * @param hostName the hostname corresponding to the IP address. 217 * @return the corresponding InetAddresses, appropriately sorted. 218 */ 219 static InetAddress[] bytesToInetAddresses(byte[][] rawAddresses, String hostName) 220 throws UnknownHostException { 221 // If we prefer IPv4, ignore the RFC3484 ordering we get from getaddrinfo(3) 222 // and always put IPv4 addresses first. Arrays.sort() is stable, so the 223 // internal ordering will not be changed. 224 if (!preferIPv6Addresses()) { 225 Arrays.sort(rawAddresses, SHORTEST_FIRST); 226 } 227 228 // Convert the byte arrays to InetAddresses. 229 InetAddress[] returnedAddresses = new InetAddress[rawAddresses.length]; 230 for (int i = 0; i < rawAddresses.length; i++) { 231 returnedAddresses[i] = makeInetAddress(rawAddresses[i], hostName); 232 } 233 return returnedAddresses; 234 } 235 236 /** 237 * Gets all IP addresses associated with the given {@code host} identified 238 * by name or literal IP address. The IP address is resolved by the 239 * configured name service. If the host name is empty or {@code null} an 240 * {@code UnknownHostException} is thrown. If the host name is a literal IP 241 * address string an array with the corresponding single {@code InetAddress} 242 * is returned. 243 * 244 * @param host the hostname or literal IP string to be resolved. 245 * @return the array of addresses associated with the specified host. 246 * @throws UnknownHostException if the address lookup fails. 247 */ 248 public static InetAddress[] getAllByName(String host) throws UnknownHostException { 249 return getAllByNameImpl(host).clone(); 250 } 251 252 /** 253 * Returns the InetAddresses for {@code host}. The returned array is shared 254 * and must be cloned before it is returned to application code. 255 */ 256 static InetAddress[] getAllByNameImpl(String host) throws UnknownHostException { 257 if (host == null || host.isEmpty()) { 258 if (preferIPv6Addresses()) { 259 return new InetAddress[] { Inet6Address.LOOPBACK, Inet4Address.LOOPBACK }; 260 } else { 261 return new InetAddress[] { Inet4Address.LOOPBACK, Inet6Address.LOOPBACK }; 262 } 263 } 264 265 // Special-case "0" for legacy IPv4 applications. 266 if (host.equals("0")) { 267 return new InetAddress[] { Inet4Address.ANY }; 268 } 269 270 // Is it a numeric address? 271 byte[] bytes = ipStringToByteArray(host); 272 if (bytes != null) { 273 return new InetAddress[] { makeInetAddress(bytes, null) }; 274 } 275 276 SecurityManager security = System.getSecurityManager(); 277 if (security != null) { 278 security.checkConnect(host, -1); 279 } 280 281 return lookupHostByName(host); 282 } 283 284 private static InetAddress makeInetAddress(byte[] bytes, String hostname) throws UnknownHostException { 285 if (bytes.length == 4) { 286 return new Inet4Address(bytes, hostname); 287 } else if (bytes.length == 16) { 288 return new Inet6Address(bytes, hostname, 0); 289 } else { 290 throw badAddressLength(bytes); 291 } 292 } 293 294 private static native String byteArrayToIpString(byte[] address); 295 296 static native byte[] ipStringToByteArray(String address); 297 298 static boolean preferIPv6Addresses() { 299 String propertyName = "java.net.preferIPv6Addresses"; 300 String propertyValue = AccessController.doPrivileged(new PriviAction<String>(propertyName)); 301 return Boolean.parseBoolean(propertyValue); 302 } 303 304 /** 305 * Returns the address of a host according to the given host string name 306 * {@code host}. The host string may be either a machine name or a dotted 307 * string IP address. If the latter, the {@code hostName} field is 308 * determined upon demand. {@code host} can be {@code null} which means that 309 * an address of the loopback interface is returned. 310 * 311 * @param host 312 * the hostName to be resolved to an address or {@code null}. 313 * @return the {@code InetAddress} instance representing the host. 314 * @throws UnknownHostException 315 * if the address lookup fails. 316 */ 317 public static InetAddress getByName(String host) throws UnknownHostException { 318 return getAllByNameImpl(host)[0]; 319 } 320 321 /** 322 * Gets the textual representation of this IP address. 323 * 324 * @return the textual representation of host's IP address. 325 */ 326 public String getHostAddress() { 327 return byteArrayToIpString(ipaddress); 328 } 329 330 /** 331 * Gets the host name of this IP address. If the IP address could not be 332 * resolved, the textual representation in a dotted-quad-notation is 333 * returned. 334 * 335 * @return the corresponding string name of this IP address. 336 */ 337 public String getHostName() { 338 try { 339 if (hostName == null) { 340 int address = 0; 341 if (ipaddress.length == 4) { 342 address = OSMemory.peekInt(ipaddress, 0, ByteOrder.BIG_ENDIAN); 343 if (address == 0) { 344 return hostName = byteArrayToIpString(ipaddress); 345 } 346 } 347 hostName = getHostByAddrImpl(ipaddress).hostName; 348 if (hostName.equals("localhost") && ipaddress.length == 4 349 && address != 0x7f000001) { 350 return hostName = byteArrayToIpString(ipaddress); 351 } 352 } 353 } catch (UnknownHostException e) { 354 return hostName = byteArrayToIpString(ipaddress); 355 } 356 SecurityManager security = System.getSecurityManager(); 357 try { 358 // Only check host names, not addresses 359 if (security != null && !isNumeric(hostName)) { 360 security.checkConnect(hostName, -1); 361 } 362 } catch (SecurityException e) { 363 return byteArrayToIpString(ipaddress); 364 } 365 return hostName; 366 } 367 368 /** 369 * Gets the fully qualified domain name for the host associated with this IP 370 * address. If a security manager is set, it is checked if the method caller 371 * is allowed to get the hostname. Otherwise, the textual representation in 372 * a dotted-quad-notation is returned. 373 * 374 * @return the fully qualified domain name of this IP address. 375 */ 376 public String getCanonicalHostName() { 377 String canonicalName; 378 try { 379 int address = 0; 380 if (ipaddress.length == 4) { 381 address = OSMemory.peekInt(ipaddress, 0, ByteOrder.BIG_ENDIAN); 382 if (address == 0) { 383 return byteArrayToIpString(ipaddress); 384 } 385 } 386 canonicalName = getHostByAddrImpl(ipaddress).hostName; 387 } catch (UnknownHostException e) { 388 return byteArrayToIpString(ipaddress); 389 } 390 SecurityManager security = System.getSecurityManager(); 391 try { 392 // Only check host names, not addresses 393 if (security != null && !isNumeric(canonicalName)) { 394 security.checkConnect(canonicalName, -1); 395 } 396 } catch (SecurityException e) { 397 return byteArrayToIpString(ipaddress); 398 } 399 return canonicalName; 400 } 401 402 /** 403 * Returns an {@code InetAddress} for the local host if possible, or the 404 * loopback address otherwise. This method works by getting the hostname, 405 * performing a DNS lookup, and then taking the first returned address. 406 * For devices with multiple network interfaces and/or multiple addresses 407 * per interface, this does not necessarily return the {@code InetAddress} 408 * you want. 409 * 410 * <p>Multiple interface/address configurations were relatively rare 411 * when this API was designed, but multiple interfaces are the default for 412 * modern mobile devices (with separate wifi and radio interfaces), and 413 * the need to support both IPv4 and IPv6 has made multiple addresses 414 * commonplace. New code should thus avoid this method except where it's 415 * basically being used to get a loopback address or equivalent. 416 * 417 * <p>There are two main ways to get a more specific answer: 418 * <ul> 419 * <li>If you have a connected socket, you should probably use 420 * {@link Socket#getLocalAddress} instead: that will give you the address 421 * that's actually in use for that connection. (It's not possible to ask 422 * the question "what local address would a connection to a given remote 423 * address use?"; you have to actually make the connection and see.)</li> 424 * <li>For other use cases, see {@link NetworkInterface}, which lets you 425 * enumerate all available network interfaces and their addresses.</li> 426 * </ul> 427 * 428 * <p>Note that if the host doesn't have a hostname set – as 429 * Android devices typically don't – this method will 430 * effectively return the loopback address, albeit by getting the name 431 * {@code localhost} and then doing a lookup to translate that to 432 * {@code 127.0.0.1}. 433 * 434 * @return an {@code InetAddress} representing the local host, or the 435 * loopback address. 436 * @throws UnknownHostException 437 * if the address lookup fails. 438 */ 439 public static InetAddress getLocalHost() throws UnknownHostException { 440 String host = gethostname(); 441 SecurityManager security = System.getSecurityManager(); 442 try { 443 if (security != null) { 444 security.checkConnect(host, -1); 445 } 446 } catch (SecurityException e) { 447 return Inet4Address.LOOPBACK; 448 } 449 return lookupHostByName(host)[0]; 450 } 451 private static native String gethostname(); 452 453 /** 454 * Gets the hashcode of the represented IP address. 455 * 456 * @return the appropriate hashcode value. 457 */ 458 @Override 459 public int hashCode() { 460 return Arrays.hashCode(ipaddress); 461 } 462 463 /* 464 * Returns whether this address is an IP multicast address or not. This 465 * implementation returns always {@code false}. 466 * 467 * @return {@code true} if this address is in the multicast group, {@code 468 * false} otherwise. 469 */ 470 public boolean isMulticastAddress() { 471 return false; 472 } 473 474 /** 475 * Resolves a hostname to its IP addresses using a cache. 476 * 477 * @param host the hostname to resolve. 478 * @return the IP addresses of the host. 479 */ 480 private static InetAddress[] lookupHostByName(String host) throws UnknownHostException { 481 BlockGuard.getThreadPolicy().onNetwork(); 482 // Do we have a result cached? 483 Object cachedResult = addressCache.get(host); 484 if (cachedResult != null) { 485 if (cachedResult instanceof InetAddress[]) { 486 // A cached positive result. 487 return (InetAddress[]) cachedResult; 488 } else { 489 // A cached negative result. 490 throw new UnknownHostException((String) cachedResult); 491 } 492 } 493 try { 494 InetAddress[] addresses = bytesToInetAddresses(getaddrinfo(host), host); 495 addressCache.put(host, addresses); 496 return addresses; 497 } catch (UnknownHostException e) { 498 String detailMessage = e.getMessage(); 499 addressCache.putUnknownHost(host, detailMessage); 500 throw new UnknownHostException(detailMessage); 501 } 502 } 503 private static native byte[][] getaddrinfo(String name) throws UnknownHostException; 504 505 /** 506 * Removes all entries from the VM's DNS cache. This does not affect the C library's DNS 507 * cache, nor any caching DNS servers between you and the canonical server. 508 * @hide 509 */ 510 public static void clearDnsCache() { 511 addressCache.clear(); 512 } 513 514 /** 515 * Query the IP stack for the host address. The host is in address form. 516 * 517 * @param addr 518 * the host address to lookup. 519 * @throws UnknownHostException 520 * if an error occurs during lookup. 521 */ 522 static InetAddress getHostByAddrImpl(byte[] addr) throws UnknownHostException { 523 BlockGuard.getThreadPolicy().onNetwork(); 524 return makeInetAddress(addr, getnameinfo(addr)); 525 } 526 527 /** 528 * Resolves an IP address to a hostname. Thread safe. 529 */ 530 private static native String getnameinfo(byte[] addr); 531 532 static String getHostNameInternal(String host, boolean isCheck) throws UnknownHostException { 533 if (host == null || host.isEmpty()) { 534 return Inet4Address.LOOPBACK.getHostAddress(); 535 } 536 if (!isNumeric(host)) { 537 if (isCheck) { 538 SecurityManager sm = System.getSecurityManager(); 539 if (sm != null) { 540 sm.checkConnect(host, -1); 541 } 542 } 543 return lookupHostByName(host)[0].getHostAddress(); 544 } 545 return host; 546 } 547 548 /** 549 * Returns a string containing a concise, human-readable description of this 550 * IP address. 551 * 552 * @return the description, as host/address. 553 */ 554 @Override 555 public String toString() { 556 return (hostName == null ? "" : hostName) + "/" + getHostAddress(); 557 } 558 559 /** 560 * Returns true if the string is a valid numeric IPv4 or IPv6 address (such as "192.168.0.1"). 561 * This copes with all forms of address that Java supports, detailed in the {@link InetAddress} 562 * class documentation. 563 * 564 * @hide - used by frameworks/base to ensure that a getAllByName won't cause a DNS lookup. 565 */ 566 public static boolean isNumeric(String address) { 567 return ipStringToByteArray(address) != null; 568 } 569 570 /** 571 * Returns whether this address is a loopback address or not. This 572 * implementation returns always {@code false}. Valid IPv4 loopback 573 * addresses are 127.d.d.d The only valid IPv6 loopback address is ::1. 574 * 575 * @return {@code true} if this instance represents a loopback address, 576 * {@code false} otherwise. 577 */ 578 public boolean isLoopbackAddress() { 579 return false; 580 } 581 582 /** 583 * Returns whether this address is a link-local address or not. This 584 * implementation returns always {@code false}. 585 * <p> 586 * Valid IPv6 link-local addresses are FE80::0 through to 587 * FEBF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF. 588 * <p> 589 * There are no valid IPv4 link-local addresses. 590 * 591 * @return {@code true} if this instance represents a link-local address, 592 * {@code false} otherwise. 593 */ 594 public boolean isLinkLocalAddress() { 595 return false; 596 } 597 598 /** 599 * Returns whether this address is a site-local address or not. This 600 * implementation returns always {@code false}. 601 * <p> 602 * Valid IPv6 site-local addresses are FEC0::0 through to 603 * FEFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF. 604 * <p> 605 * There are no valid IPv4 site-local addresses. 606 * 607 * @return {@code true} if this instance represents a site-local address, 608 * {@code false} otherwise. 609 */ 610 public boolean isSiteLocalAddress() { 611 return false; 612 } 613 614 /** 615 * Returns whether this address is a global multicast address or not. This 616 * implementation returns always {@code false}. 617 * <p> 618 * Valid IPv6 link-global multicast addresses are FFxE:/112 where x is a set 619 * of flags, and the additional 112 bits make up the global multicast 620 * address space. 621 * <p> 622 * Valid IPv4 global multicast addresses are between: 224.0.1.0 to 623 * 238.255.255.255. 624 * 625 * @return {@code true} if this instance represents a global multicast 626 * address, {@code false} otherwise. 627 */ 628 public boolean isMCGlobal() { 629 return false; 630 } 631 632 /** 633 * Returns whether this address is a node-local multicast address or not. 634 * This implementation returns always {@code false}. 635 * <p> 636 * Valid IPv6 node-local multicast addresses are FFx1:/112 where x is a set 637 * of flags, and the additional 112 bits make up the node-local multicast 638 * address space. 639 * <p> 640 * There are no valid IPv4 node-local multicast addresses. 641 * 642 * @return {@code true} if this instance represents a node-local multicast 643 * address, {@code false} otherwise. 644 */ 645 public boolean isMCNodeLocal() { 646 return false; 647 } 648 649 /** 650 * Returns whether this address is a link-local multicast address or not. 651 * This implementation returns always {@code false}. 652 * <p> 653 * Valid IPv6 link-local multicast addresses are FFx2:/112 where x is a set 654 * of flags, and the additional 112 bits make up the link-local multicast 655 * address space. 656 * <p> 657 * Valid IPv4 link-local addresses are between: 224.0.0.0 to 224.0.0.255 658 * 659 * @return {@code true} if this instance represents a link-local multicast 660 * address, {@code false} otherwise. 661 */ 662 public boolean isMCLinkLocal() { 663 return false; 664 } 665 666 /** 667 * Returns whether this address is a site-local multicast address or not. 668 * This implementation returns always {@code false}. 669 * <p> 670 * Valid IPv6 site-local multicast addresses are FFx5:/112 where x is a set 671 * of flags, and the additional 112 bits make up the site-local multicast 672 * address space. 673 * <p> 674 * Valid IPv4 site-local addresses are between: 239.252.0.0 to 675 * 239.255.255.255 676 * 677 * @return {@code true} if this instance represents a site-local multicast 678 * address, {@code false} otherwise. 679 */ 680 public boolean isMCSiteLocal() { 681 return false; 682 } 683 684 /** 685 * Returns whether this address is a organization-local multicast address or 686 * not. This implementation returns always {@code false}. 687 * <p> 688 * Valid IPv6 organization-local multicast addresses are FFx8:/112 where x 689 * is a set of flags, and the additional 112 bits make up the 690 * organization-local multicast address space. 691 * <p> 692 * Valid IPv4 organization-local addresses are between: 239.192.0.0 to 693 * 239.251.255.255 694 * 695 * @return {@code true} if this instance represents a organization-local 696 * multicast address, {@code false} otherwise. 697 */ 698 public boolean isMCOrgLocal() { 699 return false; 700 } 701 702 /** 703 * Returns whether this is a wildcard address or not. This implementation 704 * returns always {@code false}. 705 * 706 * @return {@code true} if this instance represents a wildcard address, 707 * {@code false} otherwise. 708 */ 709 public boolean isAnyLocalAddress() { 710 return false; 711 } 712 713 /** 714 * Tries to reach this {@code InetAddress}. This method first tries to use 715 * ICMP <i>(ICMP ECHO REQUEST)</i>. When first step fails, a TCP connection 716 * on port 7 (Echo) of the remote host is established. 717 * 718 * @param timeout 719 * timeout in milliseconds before the test fails if no connection 720 * could be established. 721 * @return {@code true} if this address is reachable, {@code false} 722 * otherwise. 723 * @throws IOException 724 * if an error occurs during an I/O operation. 725 * @throws IllegalArgumentException 726 * if timeout is less than zero. 727 */ 728 public boolean isReachable(int timeout) throws IOException { 729 return isReachable(null, 0, timeout); 730 } 731 732 /** 733 * Tries to reach this {@code InetAddress}. This method first tries to use 734 * ICMP <i>(ICMP ECHO REQUEST)</i>. When first step fails, a TCP connection 735 * on port 7 (Echo) of the remote host is established. 736 * 737 * @param networkInterface 738 * the network interface on which to connection should be 739 * established. 740 * @param ttl 741 * the maximum count of hops (time-to-live). 742 * @param timeout 743 * timeout in milliseconds before the test fails if no connection 744 * could be established. 745 * @return {@code true} if this address is reachable, {@code false} 746 * otherwise. 747 * @throws IOException 748 * if an error occurs during an I/O operation. 749 * @throws IllegalArgumentException 750 * if ttl or timeout is less than zero. 751 */ 752 public boolean isReachable(NetworkInterface networkInterface, final int ttl, 753 final int timeout) throws IOException { 754 if (ttl < 0 || timeout < 0) { 755 throw new IllegalArgumentException("ttl < 0 || timeout < 0"); 756 } 757 if (networkInterface == null) { 758 return isReachableByTCP(this, null, timeout); 759 } else { 760 return isReachableByMultiThread(networkInterface, ttl, timeout); 761 } 762 } 763 764 /* 765 * Uses multi-Thread to try if isReachable, returns true if any of threads 766 * returns in time 767 */ 768 private boolean isReachableByMultiThread(NetworkInterface netif, 769 final int ttl, final int timeout) 770 throws IOException { 771 List<InetAddress> addresses = Collections.list(netif.getInetAddresses()); 772 if (addresses.isEmpty()) { 773 return false; 774 } 775 reached = false; 776 addrCount = addresses.size(); 777 boolean needWait = false; 778 for (final InetAddress addr : addresses) { 779 // loopback interface can only reach to local addresses 780 if (addr.isLoopbackAddress()) { 781 Enumeration<NetworkInterface> NetworkInterfaces = NetworkInterface 782 .getNetworkInterfaces(); 783 while (NetworkInterfaces.hasMoreElements()) { 784 NetworkInterface networkInterface = NetworkInterfaces 785 .nextElement(); 786 Enumeration<InetAddress> localAddresses = networkInterface 787 .getInetAddresses(); 788 while (localAddresses.hasMoreElements()) { 789 if (InetAddress.this.equals(localAddresses 790 .nextElement())) { 791 return true; 792 } 793 } 794 } 795 796 synchronized (waitReachable) { 797 addrCount--; 798 799 if (addrCount == 0) { 800 // if count equals zero, all thread 801 // expired,notifies main thread 802 waitReachable.notifyAll(); 803 } 804 } 805 continue; 806 } 807 808 needWait = true; 809 new Thread() { 810 @Override public void run() { 811 /* 812 * Spec violation! This implementation doesn't attempt an 813 * ICMP; it skips right to TCP echo. 814 */ 815 boolean threadReached = false; 816 try { 817 threadReached = isReachableByTCP(addr, InetAddress.this, timeout); 818 } catch (IOException e) { 819 } 820 821 synchronized (waitReachable) { 822 if (threadReached) { 823 // if thread reached this address, sets reached to 824 // true and notifies main thread 825 reached = true; 826 waitReachable.notifyAll(); 827 } else { 828 addrCount--; 829 if (addrCount == 0) { 830 // if count equals zero, all thread 831 // expired,notifies main thread 832 waitReachable.notifyAll(); 833 } 834 } 835 } 836 } 837 }.start(); 838 } 839 840 if (needWait) { 841 synchronized (waitReachable) { 842 try { 843 while (!reached && (addrCount != 0)) { 844 // wait for notification 845 waitReachable.wait(1000); 846 } 847 } catch (InterruptedException e) { 848 // do nothing 849 } 850 return reached; 851 } 852 } 853 854 return false; 855 } 856 857 private boolean isReachableByTCP(InetAddress destination, InetAddress source, int timeout) 858 throws IOException { 859 FileDescriptor fd = new FileDescriptor(); 860 boolean reached = false; 861 Platform.NETWORK.socket(fd, true); 862 try { 863 if (source != null) { 864 Platform.NETWORK.bind(fd, source, 0); 865 } 866 Platform.NETWORK.connect(fd, destination, 7, timeout); 867 reached = true; 868 } catch (IOException e) { 869 if (ERRMSG_CONNECTION_REFUSED.equals(e.getMessage())) { 870 // Connection refused means the IP is reachable 871 reached = true; 872 } 873 } 874 875 Platform.NETWORK.close(fd); 876 877 return reached; 878 } 879 880 /** 881 * Returns the {@code InetAddress} corresponding to the array of bytes. In 882 * the case of an IPv4 address there must be exactly 4 bytes and for IPv6 883 * exactly 16 bytes. If not, an {@code UnknownHostException} is thrown. 884 * <p> 885 * The IP address is not validated by a name service. 886 * <p> 887 * The high order byte is {@code ipAddress[0]}. 888 * 889 * @param ipAddress 890 * is either a 4 (IPv4) or 16 (IPv6) byte long array. 891 * @return an {@code InetAddress} instance representing the given IP address 892 * {@code ipAddress}. 893 * @throws UnknownHostException 894 * if the given byte array has no valid length. 895 */ 896 public static InetAddress getByAddress(byte[] ipAddress) 897 throws UnknownHostException { 898 // simply call the method by the same name specifying the default scope 899 // id of 0 900 return getByAddressInternal(null, ipAddress, 0); 901 } 902 903 /** 904 * Returns the {@code InetAddress} corresponding to the array of bytes. In 905 * the case of an IPv4 address there must be exactly 4 bytes and for IPv6 906 * exactly 16 bytes. If not, an {@code UnknownHostException} is thrown. The 907 * IP address is not validated by a name service. The high order byte is 908 * {@code ipAddress[0]}. 909 * 910 * @param ipAddress 911 * either a 4 (IPv4) or 16 (IPv6) byte array. 912 * @param scope_id 913 * the scope id for an IPV6 scoped address. If not a scoped 914 * address just pass in 0. 915 * @return the InetAddress 916 * @throws UnknownHostException 917 */ 918 static InetAddress getByAddress(byte[] ipAddress, int scope_id) 919 throws UnknownHostException { 920 return getByAddressInternal(null, ipAddress, scope_id); 921 } 922 923 private static boolean isIPv4MappedAddress(byte[] ipAddress) { 924 // Check if the address matches ::FFFF:d.d.d.d 925 // The first 10 bytes are 0. The next to are -1 (FF). 926 // The last 4 bytes are varied. 927 if (ipAddress == null || ipAddress.length != 16) { 928 return false; 929 } 930 for (int i = 0; i < 10; i++) { 931 if (ipAddress[i] != 0) { 932 return false; 933 } 934 } 935 if (ipAddress[10] != -1 || ipAddress[11] != -1) { 936 return false; 937 } 938 return true; 939 } 940 941 private static byte[] ipv4MappedToIPv4(byte[] mappedAddress) { 942 byte[] ipv4Address = new byte[4]; 943 for(int i = 0; i < 4; i++) { 944 ipv4Address[i] = mappedAddress[12 + i]; 945 } 946 return ipv4Address; 947 } 948 949 /** 950 * Returns the {@code InetAddress} corresponding to the array of bytes, and 951 * the given hostname. In the case of an IPv4 address there must be exactly 952 * 4 bytes and for IPv6 exactly 16 bytes. If not, an {@code 953 * UnknownHostException} will be thrown. 954 * <p> 955 * The host name and IP address are not validated. 956 * <p> 957 * The hostname either be a machine alias or a valid IPv6 or IPv4 address 958 * format. 959 * <p> 960 * The high order byte is {@code ipAddress[0]}. 961 * 962 * @param hostName 963 * the string representation of hostname or IP address. 964 * @param ipAddress 965 * either a 4 (IPv4) or 16 (IPv6) byte long array. 966 * @return an {@code InetAddress} instance representing the given IP address 967 * and hostname. 968 * @throws UnknownHostException 969 * if the given byte array has no valid length. 970 */ 971 public static InetAddress getByAddress(String hostName, byte[] ipAddress) 972 throws UnknownHostException { 973 // just call the method by the same name passing in a default scope id 974 // of 0 975 return getByAddressInternal(hostName, ipAddress, 0); 976 } 977 978 /** 979 * Returns the {@code InetAddress} corresponding to the array of bytes, and 980 * the given hostname. In the case of an IPv4 address there must be exactly 981 * 4 bytes and for IPv6 exactly 16 bytes. If not, an {@code 982 * UnknownHostException} is thrown. The host name and IP address are not 983 * validated. The hostname either be a machine alias or a valid IPv6 or IPv4 984 * address format. The high order byte is {@code ipAddress[0]}. 985 * 986 * @param hostName 987 * string representation of hostname or IP address. 988 * @param ipAddress 989 * either a 4 (IPv4) or 16 (IPv6) byte array. 990 * @param scope_id 991 * the scope id for a scoped address. If not a scoped address 992 * just pass in 0. 993 * @return the InetAddress 994 * @throws UnknownHostException 995 */ 996 static InetAddress getByAddressInternal(String hostName, byte[] ipAddress, int scope_id) 997 throws UnknownHostException { 998 if (ipAddress == null) { 999 throw new UnknownHostException("ipAddress == null"); 1000 } 1001 if (ipAddress.length == 4) { 1002 return new Inet4Address(ipAddress.clone(), hostName); 1003 } else if (ipAddress.length == 16) { 1004 // First check to see if the address is an IPv6-mapped 1005 // IPv4 address. If it is, then we can make it a IPv4 1006 // address, otherwise, we'll create an IPv6 address. 1007 if (isIPv4MappedAddress(ipAddress)) { 1008 return new Inet4Address(ipv4MappedToIPv4(ipAddress), hostName); 1009 } else { 1010 return new Inet6Address(ipAddress.clone(), hostName, scope_id); 1011 } 1012 } else { 1013 throw badAddressLength(ipAddress); 1014 } 1015 } 1016 1017 private static UnknownHostException badAddressLength(byte[] bytes) throws UnknownHostException { 1018 throw new UnknownHostException("Address is neither 4 or 16 bytes: " + Arrays.toString(bytes)); 1019 } 1020 1021 private static final ObjectStreamField[] serialPersistentFields = { 1022 new ObjectStreamField("address", Integer.TYPE), 1023 new ObjectStreamField("family", Integer.TYPE), 1024 new ObjectStreamField("hostName", String.class) }; 1025 1026 private void writeObject(ObjectOutputStream stream) throws IOException { 1027 ObjectOutputStream.PutField fields = stream.putFields(); 1028 if (ipaddress == null) { 1029 fields.put("address", 0); 1030 } else { 1031 fields.put("address", OSMemory.peekInt(ipaddress, 0, ByteOrder.BIG_ENDIAN)); 1032 } 1033 fields.put("family", family); 1034 fields.put("hostName", hostName); 1035 1036 stream.writeFields(); 1037 } 1038 1039 private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { 1040 ObjectInputStream.GetField fields = stream.readFields(); 1041 int addr = fields.get("address", 0); 1042 ipaddress = new byte[4]; 1043 OSMemory.pokeInt(ipaddress, 0, addr, ByteOrder.BIG_ENDIAN); 1044 hostName = (String) fields.get("hostName", null); 1045 family = fields.get("family", 2); 1046 } 1047 1048 /* 1049 * The spec requires that if we encounter a generic InetAddress in 1050 * serialized form then we should interpret it as an Inet4 address. 1051 */ 1052 private Object readResolve() throws ObjectStreamException { 1053 return new Inet4Address(ipaddress, hostName); 1054 } 1055} 1056