1 /* 2 * Copyright (c) 1995, 2021, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package java.net; 27 28 import java.net.spi.InetAddressResolver; 29 import java.net.spi.InetAddressResolverProvider; 30 import java.net.spi.InetAddressResolver.LookupPolicy; 31 import java.security.AccessController; 32 import java.security.PrivilegedAction; 33 import java.util.List; 34 import java.util.NavigableSet; 35 import java.util.ArrayList; 36 import java.util.Objects; 37 import java.util.Scanner; 38 import java.io.File; 39 import java.io.ObjectStreamException; 40 import java.io.ObjectStreamField; 41 import java.io.IOException; 42 import java.io.InvalidObjectException; 43 import java.io.ObjectInputStream; 44 import java.io.ObjectInputStream.GetField; 45 import java.io.ObjectOutputStream; 46 import java.io.ObjectOutputStream.PutField; 47 import java.lang.annotation.Native; 48 import java.util.ServiceLoader; 49 import java.util.concurrent.ConcurrentHashMap; 50 import java.util.concurrent.ConcurrentMap; 51 import java.util.concurrent.ConcurrentSkipListSet; 52 import java.util.concurrent.atomic.AtomicLong; 53 import java.util.Arrays; 54 import java.util.concurrent.locks.ReentrantLock; 55 import java.util.stream.Stream; 56 57 import jdk.internal.misc.VM; 58 59 import jdk.internal.access.JavaNetInetAddressAccess; 60 import jdk.internal.access.SharedSecrets; 61 import sun.net.ResolverProviderConfiguration; 62 import sun.security.action.*; 63 import sun.net.InetAddressCachePolicy; 64 import sun.net.util.IPAddressUtil; 65 import sun.nio.cs.UTF_8; 66 67 import static java.net.spi.InetAddressResolver.LookupPolicy.IPV4; 68 import static java.net.spi.InetAddressResolver.LookupPolicy.IPV4_FIRST; 69 import static java.net.spi.InetAddressResolver.LookupPolicy.IPV6; 70 import static java.net.spi.InetAddressResolver.LookupPolicy.IPV6_FIRST; 71 72 /** 73 * This class represents an Internet Protocol (IP) address. 74 * 75 * <p> An IP address is either a 32-bit or 128-bit unsigned number 76 * used by IP, a lower-level protocol on which protocols like UDP and 77 * TCP are built. The IP address architecture is defined by <a 78 * href="http://www.ietf.org/rfc/rfc790.txt"><i>RFC 790: 79 * Assigned Numbers</i></a>, <a 80 * href="http://www.ietf.org/rfc/rfc1918.txt"> <i>RFC 1918: 81 * Address Allocation for Private Internets</i></a>, <a 82 * href="http://www.ietf.org/rfc/rfc2365.txt"><i>RFC 2365: 83 * Administratively Scoped IP Multicast</i></a>, and <a 84 * href="http://www.ietf.org/rfc/rfc2373.txt"><i>RFC 2373: IP 85 * Version 6 Addressing Architecture</i></a>. An instance of an 86 * InetAddress consists of an IP address and possibly its 87 * corresponding host name (depending on whether it is constructed 88 * with a host name or whether it has already done reverse host name 89 * resolution). 90 * 91 * <h2> Address types </h2> 92 * 93 * <table class="striped" style="margin-left:2em"> 94 * <caption style="display:none">Description of unicast and multicast address types</caption> 95 * <thead> 96 * <tr><th scope="col">Address Type</th><th scope="col">Description</th></tr> 97 * </thead> 98 * <tbody> 99 * <tr><th scope="row" style="vertical-align:top">unicast</th> 100 * <td>An identifier for a single interface. A packet sent to 101 * a unicast address is delivered to the interface identified by 102 * that address. 103 * 104 * <p> The Unspecified Address -- Also called anylocal or wildcard 105 * address. It must never be assigned to any node. It indicates the 106 * absence of an address. One example of its use is as the target of 107 * bind, which allows a server to accept a client connection on any 108 * interface, in case the server host has multiple interfaces. 109 * 110 * <p> The <i>unspecified</i> address must not be used as 111 * the destination address of an IP packet. 112 * 113 * <p> The <i>Loopback</i> Addresses -- This is the address 114 * assigned to the loopback interface. Anything sent to this 115 * IP address loops around and becomes IP input on the local 116 * host. This address is often used when testing a 117 * client.</td></tr> 118 * <tr><th scope="row" style="vertical-align:top">multicast</th> 119 * <td>An identifier for a set of interfaces (typically belonging 120 * to different nodes). A packet sent to a multicast address is 121 * delivered to all interfaces identified by that address.</td></tr> 122 * </tbody> 123 * </table> 124 * 125 * <h3> IP address scope </h3> 126 * 127 * <p> <i>Link-local</i> addresses are designed to be used for addressing 128 * on a single link for purposes such as auto-address configuration, 129 * neighbor discovery, or when no routers are present. 130 * 131 * <p> <i>Site-local</i> addresses are designed to be used for addressing 132 * inside of a site without the need for a global prefix. 133 * 134 * <p> <i>Global</i> addresses are unique across the internet. 135 * 136 * <h3> Textual representation of IP addresses </h3> 137 * 138 * The textual representation of an IP address is address family specific. 139 * 140 * <p> 141 * 142 * For IPv4 address format, please refer to <A 143 * HREF="Inet4Address.html#format">Inet4Address#format</A>; For IPv6 144 * address format, please refer to <A 145 * HREF="Inet6Address.html#format">Inet6Address#format</A>. 146 * 147 * <P>There is a <a href="doc-files/net-properties.html#Ipv4IPv6">couple of 148 * System Properties</a> affecting how IPv4 and IPv6 addresses are used.</P> 149 * 150 * <h3> Host Name Resolution </h3> 151 * 152 * Host name-to-IP address <i>resolution</i> is accomplished through 153 * the use of a combination of local machine configuration information 154 * and network naming services such as the Domain Name System (DNS) 155 * and Network Information Service(NIS). The particular naming 156 * services(s) being used is by default the local machine configured 157 * one. For any host name, its corresponding IP address is returned. 158 * 159 * <p> <i>Reverse name resolution</i> means that for any IP address, 160 * the host associated with the IP address is returned. 161 * 162 * <p> The InetAddress class provides methods to resolve host names to 163 * their IP addresses and vice versa. 164 * 165 * <h3> InetAddress Caching </h3> 166 * 167 * The InetAddress class has a cache to store successful as well as 168 * unsuccessful host name resolutions. 169 * 170 * <p> By default, when a security manager is installed, in order to 171 * protect against DNS spoofing attacks, 172 * the result of positive host name resolutions are 173 * cached forever. When a security manager is not installed, the default 174 * behavior is to cache entries for a finite (implementation dependent) 175 * period of time. The result of unsuccessful host 176 * name resolution is cached for a very short period of time (10 177 * seconds) to improve performance. 178 * 179 * <p> If the default behavior is not desired, then a Java security property 180 * can be set to a different Time-to-live (TTL) value for positive 181 * caching. Likewise, a system admin can configure a different 182 * negative caching TTL value when needed. 183 * 184 * <p> Two Java security properties control the TTL values used for 185 * positive and negative host name resolution caching: 186 * 187 * <dl style="margin-left:2em"> 188 * <dt><b>networkaddress.cache.ttl</b></dt> 189 * <dd>Indicates the caching policy for successful name lookups from 190 * the name service. The value is specified as an integer to indicate 191 * the number of seconds to cache the successful lookup. The default 192 * setting is to cache for an implementation specific period of time. 193 * <p> 194 * A value of -1 indicates "cache forever". 195 * </dd> 196 * <dt><b>networkaddress.cache.negative.ttl</b> (default: 10)</dt> 197 * <dd>Indicates the caching policy for un-successful name lookups 198 * from the name service. The value is specified as an integer to 199 * indicate the number of seconds to cache the failure for 200 * un-successful lookups. 201 * <p> 202 * A value of 0 indicates "never cache". 203 * A value of -1 indicates "cache forever". 204 * </dd> 205 * </dl> 206 * 207 * <h3 id="resolverProviders"> InetAddress Resolver Providers </h3> 208 * 209 * <p> Host name resolution and reverse name resolution operations are delegated to a 210 * {@linkplain InetAddressResolver resolver}. Lookup operations performed by 211 * this class use the <i>system-wide resolver</i>. The system-wide resolver 212 * is set once, lazily, after the VM is fully initialized and when 213 * an invocation of a method in this class triggers the first lookup operation. 214 * 215 * <p> A <i>custom resolver</i> can be installed as the system-wide resolver 216 * by deploying a {@linkplain InetAddressResolverProvider resolver provider}. 217 * A resolver provider is essentially a factory for resolvers, and is used 218 * to instantiate a custom resolver. If no resolver provider 219 * is found, then the <i>built-in resolver</i> will be set as the 220 * system-wide resolver. 221 * 222 * <p> A custom resolver is found and installed as the system-wide resolver 223 * as follows: 224 * <ol> 225 * <li>The {@link ServiceLoader} mechanism is used to locate an 226 * {@link InetAddressResolverProvider InetAddressResolverProvider} using the 227 * system class loader. The order in which providers are located is 228 * {@linkplain ServiceLoader#load(java.lang.Class, java.lang.ClassLoader) implementation specific}. 229 * The first provider found will be used to instantiate the {@link InetAddressResolver InetAddressResolver} 230 * by invoking the {@link InetAddressResolverProvider#get(InetAddressResolverProvider.Configuration)} 231 * method. The instantiated {@code InetAddressResolver} will be installed as the system-wide 232 * resolver. 233 * <li>If the previous step fails to find any resolver provider the 234 * built-in resolver will be set as the system-wide resolver. 235 * </ol> 236 * 237 * <p> If instantiating a custom resolver from a provider discovered in 238 * step 1 throws an error or exception, the system-wide resolver will not be 239 * installed and the error or exception will be propagated to the calling thread. 240 * Otherwise, any lookup operation will be performed through the installed 241 * <i>system-wide resolver</i>. 242 * @implNote 243 * For any lookup operation that might occur before the VM is fully booted the <i>built-in 244 * resolver</i> will be used. 245 * 246 * @author Chris Warth 247 * @see java.net.InetAddress#getByAddress(byte[]) 248 * @see java.net.InetAddress#getByAddress(java.lang.String, byte[]) 249 * @see java.net.InetAddress#getAllByName(java.lang.String) 250 * @see java.net.InetAddress#getByName(java.lang.String) 251 * @see java.net.InetAddress#getLocalHost() 252 * @since 1.0 253 */ 254 public class InetAddress implements java.io.Serializable { 255 256 /** 257 * Specify the address family: Internet Protocol, Version 4 258 * @since 1.4 259 */ 260 @Native static final int IPv4 = 1; 261 262 /** 263 * Specify the address family: Internet Protocol, Version 6 264 * @since 1.4 265 */ 266 @Native static final int IPv6 = 2; 267 268 static class InetAddressHolder { 269 /** 270 * Reserve the original application specified hostname. 271 * 272 * The original hostname is useful for domain-based endpoint 273 * identification (see RFC 2818 and RFC 6125). If an address 274 * was created with a raw IP address, a reverse name lookup 275 * may introduce endpoint identification security issue via 276 * DNS forging. 277 * 278 * Oracle JSSE provider is using this original hostname, via 279 * jdk.internal.misc.JavaNetAccess, for SSL/TLS endpoint identification. 280 * 281 * Note: May define a new public method in the future if necessary. 282 */ 283 String originalHostName; 284 285 InetAddressHolder() {} 286 287 InetAddressHolder(String hostName, int address, int family) { 288 this.originalHostName = hostName; 289 this.hostName = hostName; 290 this.address = address; 291 this.family = family; 292 } 293 294 void init(String hostName, int family) { 295 this.originalHostName = hostName; 296 this.hostName = hostName; 297 if (family != -1) { 298 this.family = family; 299 } 300 } 301 302 String hostName; 303 304 String getHostName() { 305 return hostName; 306 } 307 308 String getOriginalHostName() { 309 return originalHostName; 310 } 311 312 /** 313 * Holds a 32-bit IPv4 address. 314 */ 315 int address; 316 317 int getAddress() { 318 return address; 319 } 320 321 /** 322 * Specifies the address family type, for instance, '1' for IPv4 323 * addresses, and '2' for IPv6 addresses. 324 */ 325 int family; 326 327 int getFamily() { 328 return family; 329 } 330 } 331 332 /* Used to store the serializable fields of InetAddress */ 333 final transient InetAddressHolder holder; 334 335 InetAddressHolder holder() { 336 return holder; 337 } 338 339 /* Used to store the system-wide resolver */ 340 private static volatile InetAddressResolver resolver; 341 342 private static final InetAddressResolver BUILTIN_RESOLVER; 343 344 /** 345 * Used to store the best available hostname. 346 * Lazily initialized via a data race; safe because Strings are immutable. 347 */ 348 private transient String canonicalHostName = null; 349 350 /** use serialVersionUID from JDK 1.0.2 for interoperability */ 351 @java.io.Serial 352 private static final long serialVersionUID = 3286316764910316507L; 353 354 // "java.net.preferIPv4Stack" system property value 355 private static final String PREFER_IPV4_STACK_VALUE; 356 357 // "java.net.preferIPv6Addresses" system property value 358 private static final String PREFER_IPV6_ADDRESSES_VALUE; 359 360 // "jdk.net.hosts.file" system property value 361 private static final String HOSTS_FILE_NAME; 362 363 /* 364 * Load net library into runtime, and perform initializations. 365 */ 366 static { 367 PREFER_IPV4_STACK_VALUE = 368 GetPropertyAction.privilegedGetProperty("java.net.preferIPv4Stack"); 369 PREFER_IPV6_ADDRESSES_VALUE = 370 GetPropertyAction.privilegedGetProperty("java.net.preferIPv6Addresses"); 371 HOSTS_FILE_NAME = 372 GetPropertyAction.privilegedGetProperty("jdk.net.hosts.file"); 373 jdk.internal.loader.BootLoader.loadLibrary("net"); 374 SharedSecrets.setJavaNetInetAddressAccess( 375 new JavaNetInetAddressAccess() { 376 public String getOriginalHostName(InetAddress ia) { 377 return ia.holder.getOriginalHostName(); 378 } 379 380 public int addressValue(Inet4Address inet4Address) { 381 return inet4Address.addressValue(); 382 } 383 384 public byte[] addressBytes(Inet6Address inet6Address) { 385 return inet6Address.addressBytes(); 386 } 387 } 388 ); 389 init(); 390 } 391 392 /** 393 * Creates an address lookup policy from {@code "java.net.preferIPv4Stack"}, 394 * {@code "java.net.preferIPv6Addresses"} system property values, and O/S configuration. 395 */ 396 private static final LookupPolicy initializePlatformLookupPolicy() { 397 // Calculate AddressFamily value first 398 boolean ipv4Available = isIPv4Available(); 399 if ("true".equals(PREFER_IPV4_STACK_VALUE) && ipv4Available) { 400 return LookupPolicy.of(IPV4); 401 } 402 // Check if IPv6 is not supported 403 if (InetAddress.impl instanceof Inet4AddressImpl) { 404 return LookupPolicy.of(IPV4); 405 } 406 // Check if system supports IPv4, if not use IPv6 407 if (!ipv4Available) { 408 return LookupPolicy.of(IPV6); 409 } 410 // If both address families are needed - check preferIPv6Addresses value 411 if (PREFER_IPV6_ADDRESSES_VALUE != null) { 412 if (PREFER_IPV6_ADDRESSES_VALUE.equalsIgnoreCase("true")) { 413 return LookupPolicy.of(IPV4 | IPV6 | IPV6_FIRST); 414 } 415 if (PREFER_IPV6_ADDRESSES_VALUE.equalsIgnoreCase("false")) { 416 return LookupPolicy.of(IPV4 | IPV6 | IPV4_FIRST); 417 } 418 if (PREFER_IPV6_ADDRESSES_VALUE.equalsIgnoreCase("system")) { 419 return LookupPolicy.of(IPV4 | IPV6); 420 } 421 } 422 // Default value with both address families needed - IPv4 addresses come first 423 return LookupPolicy.of(IPV4 | IPV6 | IPV4_FIRST); 424 } 425 426 static boolean systemAddressesOrder(int lookupCharacteristics) { 427 return (lookupCharacteristics & (IPV4_FIRST | IPV6_FIRST)) == 0; 428 } 429 430 static boolean ipv4AddressesFirst(int lookupCharacteristics) { 431 return (lookupCharacteristics & IPV4_FIRST) != 0; 432 } 433 434 static boolean ipv6AddressesFirst(int lookupCharacteristics) { 435 return (lookupCharacteristics & IPV6_FIRST) != 0; 436 } 437 438 // Native method to check if IPv4 is available 439 private static native boolean isIPv4Available(); 440 441 /** 442 * The {@code RuntimePermission("inetAddressResolverProvider")} is 443 * necessary to subclass and instantiate the {@code InetAddressResolverProvider} 444 * class, as well as to obtain resolver from an instance of that class, 445 * and it is also required to obtain the operating system name resolution configurations. 446 */ 447 private static final RuntimePermission INET_ADDRESS_RESOLVER_PERMISSION = 448 new RuntimePermission("inetAddressResolverProvider"); 449 450 private static final ReentrantLock RESOLVER_LOCK = new ReentrantLock(); 451 private static volatile InetAddressResolver bootstrapResolver; 452 453 @SuppressWarnings("removal") 454 private static InetAddressResolver resolver() { 455 InetAddressResolver cns = resolver; 456 if (cns != null) { 457 return cns; 458 } 459 if (VM.isBooted()) { 460 RESOLVER_LOCK.lock(); 461 try { 462 cns = resolver; 463 if (cns != null) { 464 return cns; 465 } 466 // Protection against provider calling InetAddress APIs during initialization 467 if (bootstrapResolver != null) { 468 return bootstrapResolver; 469 } else { 470 bootstrapResolver = BUILTIN_RESOLVER; 471 } 472 if (HOSTS_FILE_NAME != null) { 473 // The default resolver service is already host file resolver 474 cns = BUILTIN_RESOLVER; 475 } else if (System.getSecurityManager() != null) { 476 PrivilegedAction<InetAddressResolver> pa = InetAddress::loadResolver; 477 cns = AccessController.doPrivileged( 478 pa, null, INET_ADDRESS_RESOLVER_PERMISSION); 479 } else { 480 cns = loadResolver(); 481 } 482 483 InetAddress.resolver = cns; 484 return cns; 485 } finally { 486 bootstrapResolver = null; 487 RESOLVER_LOCK.unlock(); 488 } 489 } else { 490 return BUILTIN_RESOLVER; 491 } 492 } 493 494 private static InetAddressResolver loadResolver() { 495 return ServiceLoader.load(InetAddressResolverProvider.class) 496 .findFirst() 497 .map(nsp -> nsp.get(builtinConfiguration())) 498 .orElse(BUILTIN_RESOLVER); 499 } 500 501 private static InetAddressResolverProvider.Configuration builtinConfiguration() { 502 return new ResolverProviderConfiguration(BUILTIN_RESOLVER, () -> { 503 try { 504 return impl.getLocalHostName(); 505 } catch (UnknownHostException unknownHostException) { 506 return "localhost"; 507 } 508 }); 509 } 510 511 /** 512 * Constructor for the Socket.accept() method. 513 * This creates an empty InetAddress, which is filled in by 514 * the accept() method. This InetAddress, however, is not 515 * put in the address cache, since it is not created by name. 516 */ 517 InetAddress() { 518 holder = new InetAddressHolder(); 519 } 520 521 /** 522 * Replaces the de-serialized object with an Inet4Address object. 523 * 524 * @return the alternate object to the de-serialized object. 525 * 526 * @throws ObjectStreamException if a new object replacing this 527 * object could not be created 528 */ 529 @java.io.Serial 530 private Object readResolve() throws ObjectStreamException { 531 // will replace the deserialized 'this' object 532 return new Inet4Address(holder().getHostName(), holder().getAddress()); 533 } 534 535 /** 536 * Utility routine to check if the InetAddress is an 537 * IP multicast address. 538 * @return a {@code boolean} indicating if the InetAddress is 539 * an IP multicast address 540 * @since 1.1 541 */ 542 public boolean isMulticastAddress() { 543 return false; 544 } 545 546 /** 547 * Utility routine to check if the InetAddress is a wildcard address. 548 * @return a {@code boolean} indicating if the InetAddress is 549 * a wildcard address. 550 * @since 1.4 551 */ 552 public boolean isAnyLocalAddress() { 553 return false; 554 } 555 556 /** 557 * Utility routine to check if the InetAddress is a loopback address. 558 * 559 * @return a {@code boolean} indicating if the InetAddress is 560 * a loopback address; or false otherwise. 561 * @since 1.4 562 */ 563 public boolean isLoopbackAddress() { 564 return false; 565 } 566 567 /** 568 * Utility routine to check if the InetAddress is a link local address. 569 * 570 * @return a {@code boolean} indicating if the InetAddress is 571 * a link local address; or false if address is not a link local unicast address. 572 * @since 1.4 573 */ 574 public boolean isLinkLocalAddress() { 575 return false; 576 } 577 578 /** 579 * Utility routine to check if the InetAddress is a site local address. 580 * 581 * @return a {@code boolean} indicating if the InetAddress is 582 * a site local address; or false if address is not a site local unicast address. 583 * @since 1.4 584 */ 585 public boolean isSiteLocalAddress() { 586 return false; 587 } 588 589 /** 590 * Utility routine to check if the multicast address has global scope. 591 * 592 * @return a {@code boolean} indicating if the address has 593 * is a multicast address of global scope, false if it is not 594 * of global scope or it is not a multicast address 595 * @since 1.4 596 */ 597 public boolean isMCGlobal() { 598 return false; 599 } 600 601 /** 602 * Utility routine to check if the multicast address has node scope. 603 * 604 * @return a {@code boolean} indicating if the address has 605 * is a multicast address of node-local scope, false if it is not 606 * of node-local scope or it is not a multicast address 607 * @since 1.4 608 */ 609 public boolean isMCNodeLocal() { 610 return false; 611 } 612 613 /** 614 * Utility routine to check if the multicast address has link scope. 615 * 616 * @return a {@code boolean} indicating if the address has 617 * is a multicast address of link-local scope, false if it is not 618 * of link-local scope or it is not a multicast address 619 * @since 1.4 620 */ 621 public boolean isMCLinkLocal() { 622 return false; 623 } 624 625 /** 626 * Utility routine to check if the multicast address has site scope. 627 * 628 * @return a {@code boolean} indicating if the address has 629 * is a multicast address of site-local scope, false if it is not 630 * of site-local scope or it is not a multicast address 631 * @since 1.4 632 */ 633 public boolean isMCSiteLocal() { 634 return false; 635 } 636 637 /** 638 * Utility routine to check if the multicast address has organization scope. 639 * 640 * @return a {@code boolean} indicating if the address has 641 * is a multicast address of organization-local scope, 642 * false if it is not of organization-local scope 643 * or it is not a multicast address 644 * @since 1.4 645 */ 646 public boolean isMCOrgLocal() { 647 return false; 648 } 649 650 651 /** 652 * Test whether that address is reachable. Best effort is made by the 653 * implementation to try to reach the host, but firewalls and server 654 * configuration may block requests resulting in an unreachable status 655 * while some specific ports may be accessible. 656 * A typical implementation will use ICMP ECHO REQUESTs if the 657 * privilege can be obtained, otherwise it will try to establish 658 * a TCP connection on port 7 (Echo) of the destination host. 659 * <p> 660 * The timeout value, in milliseconds, indicates the maximum amount of time 661 * the try should take. If the operation times out before getting an 662 * answer, the host is deemed unreachable. A negative value will result 663 * in an IllegalArgumentException being thrown. 664 * 665 * @param timeout the time, in milliseconds, before the call aborts 666 * @return a {@code boolean} indicating if the address is reachable. 667 * @throws IOException if a network error occurs 668 * @throws IllegalArgumentException if {@code timeout} is negative. 669 * @since 1.5 670 */ 671 public boolean isReachable(int timeout) throws IOException { 672 return isReachable(null, 0 , timeout); 673 } 674 675 /** 676 * Test whether that address is reachable. Best effort is made by the 677 * implementation to try to reach the host, but firewalls and server 678 * configuration may block requests resulting in a unreachable status 679 * while some specific ports may be accessible. 680 * A typical implementation will use ICMP ECHO REQUESTs if the 681 * privilege can be obtained, otherwise it will try to establish 682 * a TCP connection on port 7 (Echo) of the destination host. 683 * <p> 684 * The {@code network interface} and {@code ttl} parameters 685 * let the caller specify which network interface the test will go through 686 * and the maximum number of hops the packets should go through. 687 * A negative value for the {@code ttl} will result in an 688 * IllegalArgumentException being thrown. 689 * <p> 690 * The timeout value, in milliseconds, indicates the maximum amount of time 691 * the try should take. If the operation times out before getting an 692 * answer, the host is deemed unreachable. A negative value will result 693 * in an IllegalArgumentException being thrown. 694 * 695 * @param netif the NetworkInterface through which the 696 * test will be done, or null for any interface 697 * @param ttl the maximum numbers of hops to try or 0 for the 698 * default 699 * @param timeout the time, in milliseconds, before the call aborts 700 * @throws IllegalArgumentException if either {@code timeout} 701 * or {@code ttl} are negative. 702 * @return a {@code boolean} indicating if the address is reachable. 703 * @throws IOException if a network error occurs 704 * @since 1.5 705 */ 706 public boolean isReachable(NetworkInterface netif, int ttl, 707 int timeout) throws IOException { 708 if (ttl < 0) 709 throw new IllegalArgumentException("ttl can't be negative"); 710 if (timeout < 0) 711 throw new IllegalArgumentException("timeout can't be negative"); 712 713 return impl.isReachable(this, timeout, netif, ttl); 714 } 715 716 /** 717 * Gets the host name for this IP address. 718 * 719 * <p>If this InetAddress was created with a host name, 720 * this host name will be remembered and returned; 721 * otherwise, a reverse name lookup will be performed 722 * and the result will be returned based on the system 723 * configured resolver. If a lookup of the name service 724 * is required, call 725 * {@link #getCanonicalHostName() getCanonicalHostName}. 726 * 727 * <p>If there is a security manager, its 728 * {@code checkConnect} method is first called 729 * with the hostname and {@code -1} 730 * as its arguments to see if the operation is allowed. 731 * If the operation is not allowed, it will return 732 * the textual representation of the IP address. 733 * 734 * @return the host name for this IP address, or if the operation 735 * is not allowed by the security check, the textual 736 * representation of the IP address. 737 * 738 * @see InetAddress#getCanonicalHostName 739 * @see SecurityManager#checkConnect 740 */ 741 public String getHostName() { 742 return getHostName(true); 743 } 744 745 /** 746 * Returns the hostname for this address. 747 * If the host is equal to null, then this address refers to any 748 * of the local machine's available network addresses. 749 * this is package private so SocketPermission can make calls into 750 * here without a security check. 751 * 752 * <p>If there is a security manager, this method first 753 * calls its {@code checkConnect} method 754 * with the hostname and {@code -1} 755 * as its arguments to see if the calling code is allowed to know 756 * the hostname for this IP address, i.e., to connect to the host. 757 * If the operation is not allowed, it will return 758 * the textual representation of the IP address. 759 * 760 * @return the host name for this IP address, or if the operation 761 * is not allowed by the security check, the textual 762 * representation of the IP address. 763 * 764 * @param check make security check if true 765 * 766 * @see SecurityManager#checkConnect 767 */ 768 String getHostName(boolean check) { 769 if (holder().getHostName() == null) { 770 holder().hostName = InetAddress.getHostFromNameService(this, check); 771 } 772 return holder().getHostName(); 773 } 774 775 /** 776 * Gets the fully qualified domain name for this IP address. 777 * Best effort method, meaning we may not be able to return 778 * the FQDN depending on the underlying system configuration. 779 * 780 * <p>If there is a security manager, this method first 781 * calls its {@code checkConnect} method 782 * with the hostname and {@code -1} 783 * as its arguments to see if the calling code is allowed to know 784 * the hostname for this IP address, i.e., to connect to the host. 785 * If the operation is not allowed, it will return 786 * the textual representation of the IP address. 787 * 788 * @return the fully qualified domain name for this IP address, 789 * or if the operation is not allowed by the security check, 790 * the textual representation of the IP address. 791 * 792 * @see SecurityManager#checkConnect 793 * 794 * @since 1.4 795 */ 796 public String getCanonicalHostName() { 797 String value = canonicalHostName; 798 if (value == null) 799 canonicalHostName = value = 800 InetAddress.getHostFromNameService(this, true); 801 return value; 802 } 803 804 /** 805 * Returns the hostname for this address. 806 * 807 * <p>If there is a security manager, this method first 808 * calls its {@code checkConnect} method 809 * with the hostname and {@code -1} 810 * as its arguments to see if the calling code is allowed to know 811 * the hostname for this IP address, i.e., to connect to the host. 812 * If the operation is not allowed, it will return 813 * the textual representation of the IP address. 814 * 815 * @return the host name for this IP address, or if the operation 816 * is not allowed by the security check, the textual 817 * representation of the IP address. 818 * 819 * @param check make security check if true 820 * 821 * @see SecurityManager#checkConnect 822 */ 823 private static String getHostFromNameService(InetAddress addr, boolean check) { 824 String host; 825 var resolver = resolver(); 826 try { 827 // first lookup the hostname 828 host = resolver.lookupHostName(addr.getAddress()); 829 830 /* check to see if calling code is allowed to know 831 * the hostname for this IP address, ie, connect to the host 832 */ 833 if (check) { 834 @SuppressWarnings("removal") 835 SecurityManager sec = System.getSecurityManager(); 836 if (sec != null) { 837 sec.checkConnect(host, -1); 838 } 839 } 840 841 /* now get all the IP addresses for this hostname, 842 * and make sure one of them matches the original IP 843 * address. We do this to try and prevent spoofing. 844 */ 845 846 InetAddress[] arr = InetAddress.getAllByName0(host, check); 847 boolean ok = false; 848 849 if (arr != null) { 850 for (int i = 0; !ok && i < arr.length; i++) { 851 ok = addr.equals(arr[i]); 852 } 853 } 854 855 //XXX: if it looks like a spoof just return the address? 856 if (!ok) { 857 host = addr.getHostAddress(); 858 return host; 859 } 860 } catch (RuntimeException | UnknownHostException e) { 861 host = addr.getHostAddress(); 862 } 863 return host; 864 } 865 866 /** 867 * Returns the raw IP address of this {@code InetAddress} 868 * object. The result is in network byte order: the highest order 869 * byte of the address is in {@code getAddress()[0]}. 870 * 871 * @return the raw IP address of this object. 872 */ 873 public byte[] getAddress() { 874 return null; 875 } 876 877 /** 878 * Returns the IP address string in textual presentation. 879 * 880 * @return the raw IP address in a string format. 881 * @since 1.0.2 882 */ 883 public String getHostAddress() { 884 return null; 885 } 886 887 /** 888 * Returns a hashcode for this IP address. 889 * 890 * @return a hash code value for this IP address. 891 */ 892 public int hashCode() { 893 return -1; 894 } 895 896 /** 897 * Compares this object against the specified object. 898 * The result is {@code true} if and only if the argument is 899 * not {@code null} and it represents the same IP address as 900 * this object. 901 * <p> 902 * Two instances of {@code InetAddress} represent the same IP 903 * address if the length of the byte arrays returned by 904 * {@code getAddress} is the same for both, and each of the 905 * array components is the same for the byte arrays. 906 * 907 * @param obj the object to compare against. 908 * @return {@code true} if the objects are the same; 909 * {@code false} otherwise. 910 * @see java.net.InetAddress#getAddress() 911 */ 912 public boolean equals(Object obj) { 913 return false; 914 } 915 916 /** 917 * Converts this IP address to a {@code String}. The 918 * string returned is of the form: hostname / literal IP 919 * address. 920 * 921 * If the host name is unresolved, no reverse lookup 922 * is performed. The hostname part will be represented 923 * by an empty string. 924 * 925 * @return a string representation of this IP address. 926 */ 927 public String toString() { 928 String hostName = holder().getHostName(); 929 return Objects.toString(hostName, "") 930 + "/" + getHostAddress(); 931 } 932 933 // mapping from host name to Addresses - either NameServiceAddresses (while 934 // still being looked-up by NameService(s)) or CachedAddresses when cached 935 private static final ConcurrentMap<String, Addresses> cache = 936 new ConcurrentHashMap<>(); 937 938 // CachedAddresses that have to expire are kept ordered in this NavigableSet 939 // which is scanned on each access 940 private static final NavigableSet<CachedAddresses> expirySet = 941 new ConcurrentSkipListSet<>(); 942 943 // common interface 944 private interface Addresses { 945 InetAddress[] get() throws UnknownHostException; 946 } 947 948 // a holder for cached addresses with required metadata 949 private static final class CachedAddresses implements Addresses, Comparable<CachedAddresses> { 950 private static final AtomicLong seq = new AtomicLong(); 951 final String host; 952 final InetAddress[] inetAddresses; 953 final long expiryTime; // time of expiry (in terms of System.nanoTime()) 954 final long id = seq.incrementAndGet(); // each instance is unique 955 956 CachedAddresses(String host, InetAddress[] inetAddresses, long expiryTime) { 957 this.host = host; 958 this.inetAddresses = inetAddresses; 959 this.expiryTime = expiryTime; 960 } 961 962 @Override 963 public InetAddress[] get() throws UnknownHostException { 964 if (inetAddresses == null) { 965 throw new UnknownHostException(host); 966 } 967 return inetAddresses; 968 } 969 970 @Override 971 public int compareTo(CachedAddresses other) { 972 // natural order is expiry time - 973 // compare difference of expiry times rather than 974 // expiry times directly, to avoid possible overflow. 975 // (see System.nanoTime() recommendations...) 976 long diff = this.expiryTime - other.expiryTime; 977 if (diff < 0L) return -1; 978 if (diff > 0L) return 1; 979 // ties are broken using unique id 980 return Long.compare(this.id, other.id); 981 } 982 } 983 984 // a name service lookup based Addresses implementation which replaces itself 985 // in cache when the result is obtained 986 private static final class NameServiceAddresses implements Addresses { 987 private final String host; 988 989 NameServiceAddresses(String host) { 990 this.host = host; 991 } 992 993 @Override 994 public InetAddress[] get() throws UnknownHostException { 995 Addresses addresses; 996 // only one thread is doing lookup to name service 997 // for particular host at any time. 998 synchronized (this) { 999 // re-check that we are still us + re-install us if slot empty 1000 addresses = cache.putIfAbsent(host, this); 1001 if (addresses == null) { 1002 // this can happen when we were replaced by CachedAddresses in 1003 // some other thread, then CachedAddresses expired and were 1004 // removed from cache while we were waiting for lock... 1005 addresses = this; 1006 } 1007 // still us ? 1008 if (addresses == this) { 1009 // lookup name services 1010 InetAddress[] inetAddresses; 1011 UnknownHostException ex; 1012 int cachePolicy; 1013 try { 1014 inetAddresses = getAddressesFromNameService(host); 1015 ex = null; 1016 cachePolicy = InetAddressCachePolicy.get(); 1017 } catch (UnknownHostException uhe) { 1018 inetAddresses = null; 1019 ex = uhe; 1020 cachePolicy = InetAddressCachePolicy.getNegative(); 1021 } 1022 // remove or replace us with cached addresses according to cachePolicy 1023 if (cachePolicy == InetAddressCachePolicy.NEVER) { 1024 cache.remove(host, this); 1025 } else { 1026 CachedAddresses cachedAddresses = new CachedAddresses( 1027 host, 1028 inetAddresses, 1029 cachePolicy == InetAddressCachePolicy.FOREVER 1030 ? 0L 1031 // cachePolicy is in [s] - we need [ns] 1032 : System.nanoTime() + 1000_000_000L * cachePolicy 1033 ); 1034 if (cache.replace(host, this, cachedAddresses) && 1035 cachePolicy != InetAddressCachePolicy.FOREVER) { 1036 // schedule expiry 1037 expirySet.add(cachedAddresses); 1038 } 1039 } 1040 if (inetAddresses == null) { 1041 throw ex == null ? new UnknownHostException(host) : ex; 1042 } 1043 return inetAddresses; 1044 } 1045 // else addresses != this 1046 } 1047 // delegate to different addresses when we are already replaced 1048 // but outside of synchronized block to avoid any chance of dead-locking 1049 return addresses.get(); 1050 } 1051 } 1052 1053 /** 1054 * The default InetAddressResolver implementation, which delegates to the underlying 1055 * OS network libraries to resolve host address mappings. 1056 * 1057 * @since 9 1058 */ 1059 private static final class PlatformResolver implements InetAddressResolver { 1060 1061 public Stream<InetAddress> lookupAddresses(String host, LookupPolicy policy) 1062 throws UnknownHostException { 1063 Objects.requireNonNull(host); 1064 return Arrays.stream(impl.lookupAllHostAddr(host, policy)); 1065 } 1066 1067 public String lookupHostName(byte[] addr) 1068 throws UnknownHostException { 1069 if (addr.length != Inet4Address.INADDRSZ && addr.length != Inet6Address.INADDRSZ) { 1070 throw new IllegalArgumentException("Invalid address length"); 1071 } 1072 return impl.getHostByAddr(addr); 1073 } 1074 } 1075 1076 /** 1077 * The HostsFileResolver provides host address mapping 1078 * by reading the entries in a hosts file, which is specified by 1079 * {@code jdk.net.hosts.file} system property 1080 * 1081 * <p>The file format is that which corresponds with the /etc/hosts file 1082 * IP Address host alias list. 1083 * 1084 * <p>When the file lookup is enabled it replaces the default InetAddressResolver 1085 * implementation 1086 * 1087 * @since 9 1088 */ 1089 private static final class HostsFileResolver implements InetAddressResolver { 1090 1091 private final String hostsFile; 1092 1093 public HostsFileResolver(String hostsFileName) { 1094 this.hostsFile = hostsFileName; 1095 } 1096 1097 /** 1098 * Lookup the host name corresponding to the IP address provided. 1099 * Search the configured host file a host name corresponding to 1100 * the specified IP address. 1101 * 1102 * @param addr byte array representing an IP address 1103 * @return {@code String} representing the host name mapping 1104 * @throws UnknownHostException if no host found for the specified IP address 1105 * @throws IllegalArgumentException if IP address is of illegal length 1106 */ 1107 @Override 1108 public String lookupHostName(byte[] addr) throws UnknownHostException { 1109 String hostEntry; 1110 String host = null; 1111 1112 // Check the length of the address array 1113 if (addr.length != Inet4Address.INADDRSZ && addr.length != Inet6Address.INADDRSZ) { 1114 throw new IllegalArgumentException("Invalid address length"); 1115 } 1116 1117 try (Scanner hostsFileScanner = new Scanner(new File(hostsFile), 1118 UTF_8.INSTANCE)) { 1119 while (hostsFileScanner.hasNextLine()) { 1120 hostEntry = hostsFileScanner.nextLine(); 1121 if (!hostEntry.startsWith("#")) { 1122 hostEntry = removeComments(hostEntry); 1123 String[] mapping = hostEntry.split("\\s+"); 1124 if (mapping.length >= 2 && 1125 Arrays.equals(addr, createAddressByteArray(mapping[0]))) { 1126 host = mapping[1]; 1127 break; 1128 } 1129 } 1130 } 1131 } catch (IOException e) { 1132 throw new UnknownHostException("Unable to resolve address " 1133 + Arrays.toString(addr) + " as hosts file " + hostsFile 1134 + " not found "); 1135 } 1136 1137 if ((host == null) || (host.isEmpty()) || (host.equals(" "))) { 1138 throw new UnknownHostException("Requested address " 1139 + Arrays.toString(addr) 1140 + " resolves to an invalid entry in hosts file " 1141 + hostsFile); 1142 } 1143 return host; 1144 } 1145 1146 /** 1147 * <p>Lookup a host mapping by name. Retrieve the IP addresses 1148 * associated with a host. 1149 * 1150 * <p>Search the configured hosts file for the addresses associated 1151 * with the specified host name. 1152 * 1153 * @param host the specified hostname 1154 * @param lookupPolicy IP addresses lookup policy which specifies addresses 1155 * family and their order 1156 * @return stream of IP addresses for the requested host 1157 * @throws UnknownHostException 1158 * if no IP address for the {@code host} could be found 1159 */ 1160 public Stream<InetAddress> lookupAddresses(String host, LookupPolicy lookupPolicy) 1161 throws UnknownHostException { 1162 String hostEntry; 1163 String addrStr; 1164 byte addr[]; 1165 List<InetAddress> inetAddresses = new ArrayList<>(); 1166 List<InetAddress> inet4Addresses = new ArrayList<>(); 1167 List<InetAddress> inet6Addresses = new ArrayList<>(); 1168 int flags = lookupPolicy.characteristics(); 1169 boolean needIPv4 = (flags & IPv4) != 0; 1170 boolean needIPv6 = (flags & IPv6) != 0; 1171 1172 Objects.requireNonNull(host); 1173 1174 // lookup the file and create a list InetAddress for the specified host 1175 try (Scanner hostsFileScanner = new Scanner(new File(hostsFile), 1176 UTF_8.INSTANCE)) { 1177 while (hostsFileScanner.hasNextLine()) { 1178 hostEntry = hostsFileScanner.nextLine(); 1179 if (!hostEntry.startsWith("#")) { 1180 hostEntry = removeComments(hostEntry); 1181 if (hostEntry.contains(host)) { 1182 addrStr = extractHostAddr(hostEntry, host); 1183 if ((addrStr != null) && (!addrStr.isEmpty())) { 1184 addr = createAddressByteArray(addrStr); 1185 if (addr != null) { 1186 InetAddress address = InetAddress.getByAddress(host, addr); 1187 inetAddresses.add(address); 1188 if (address instanceof Inet4Address && needIPv4) { 1189 inet4Addresses.add(address); 1190 } 1191 if (address instanceof Inet6Address && needIPv6) { 1192 inet6Addresses.add(address); 1193 } 1194 } 1195 } 1196 } 1197 } 1198 } 1199 } catch (IOException e) { 1200 throw new UnknownHostException("Unable to resolve host " + host 1201 + " as hosts file " + hostsFile + " not found "); 1202 } 1203 // Check number of found addresses: 1204 // If none found - throw an exception 1205 boolean noAddressFound = inetAddresses.isEmpty(); 1206 // needIPv4 == false and needIPv6 is not a valid combination. See LookupPolicy.of. 1207 if (needIPv4 != needIPv6) { 1208 if (needIPv4) { 1209 noAddressFound = inet4Addresses.isEmpty(); 1210 } else { 1211 noAddressFound = inet6Addresses.isEmpty(); 1212 } 1213 } 1214 if (noAddressFound) { 1215 throw new UnknownHostException("Unable to resolve host " + host 1216 + " in hosts file " + hostsFile); 1217 } 1218 1219 // If both address types are requested 1220 if (needIPv4 == needIPv6) { 1221 if (systemAddressesOrder(flags)) { 1222 return inetAddresses.stream(); 1223 } else if (ipv6AddressesFirst(flags)) { 1224 return Stream.concat(inet6Addresses.stream(), inet4Addresses.stream()); 1225 } else if (ipv4AddressesFirst(flags)) { 1226 return Stream.concat(inet4Addresses.stream(), inet6Addresses.stream()); 1227 } 1228 } 1229 // Only IPv4 addresses are requested 1230 if (needIPv4) { 1231 return inet4Addresses.stream(); 1232 } 1233 // Only IPv6 addresses are requested 1234 return inet6Addresses.stream(); 1235 } 1236 1237 private String removeComments(String hostsEntry) { 1238 String filteredEntry = hostsEntry; 1239 int hashIndex; 1240 1241 if ((hashIndex = hostsEntry.indexOf("#")) != -1) { 1242 filteredEntry = hostsEntry.substring(0, hashIndex); 1243 } 1244 return filteredEntry; 1245 } 1246 1247 private byte [] createAddressByteArray(String addrStr) { 1248 byte[] addrArray; 1249 // check if IPV4 address - most likely 1250 addrArray = IPAddressUtil.textToNumericFormatV4(addrStr); 1251 if (addrArray == null) { 1252 addrArray = IPAddressUtil.textToNumericFormatV6(addrStr); 1253 } 1254 return addrArray; 1255 } 1256 1257 /** host to ip address mapping */ 1258 private String extractHostAddr(String hostEntry, String host) { 1259 String[] mapping = hostEntry.split("\\s+"); 1260 String hostAddr = null; 1261 1262 if (mapping.length >= 2) { 1263 // look at the host aliases 1264 for (int i = 1; i < mapping.length; i++) { 1265 if (mapping[i].equalsIgnoreCase(host)) { 1266 hostAddr = mapping[0]; 1267 } 1268 } 1269 } 1270 return hostAddr; 1271 } 1272 } 1273 1274 static final InetAddressImpl impl; 1275 1276 /** 1277 * Platform-wide {@code LookupPolicy} initialized from {@code "java.net.preferIPv4Stack"}, 1278 * {@code "java.net.preferIPv6Addresses"} system properties. 1279 */ 1280 static final LookupPolicy PLATFORM_LOOKUP_POLICY; 1281 1282 static { 1283 // create the impl 1284 impl = InetAddressImplFactory.create(); 1285 1286 // impl must be initialized before calling this method 1287 PLATFORM_LOOKUP_POLICY = initializePlatformLookupPolicy(); 1288 1289 // create built-in resolver 1290 BUILTIN_RESOLVER = createBuiltinInetAddressResolver(); 1291 } 1292 1293 /** 1294 * Create an instance of the InetAddressResolver interface based on 1295 * the setting of the {@code jdk.net.hosts.file} system property. 1296 * 1297 * <p>The default InetAddressResolver is the PlatformResolver, which typically 1298 * delegates name and address resolution calls to the underlying 1299 * OS network libraries. 1300 * 1301 * <p> A HostsFileResolver is created if the {@code jdk.net.hosts.file} 1302 * system property is set. If the specified file doesn't exist, the name or 1303 * address lookup will result in an UnknownHostException. Thus, non existent 1304 * hosts file is handled as if the file is empty. 1305 * 1306 * @return an InetAddressResolver 1307 */ 1308 private static InetAddressResolver createBuiltinInetAddressResolver() { 1309 InetAddressResolver theResolver; 1310 if (HOSTS_FILE_NAME != null) { 1311 theResolver = new HostsFileResolver(HOSTS_FILE_NAME); 1312 } else { 1313 theResolver = new PlatformResolver(); 1314 } 1315 return theResolver; 1316 } 1317 1318 /** 1319 * Creates an InetAddress based on the provided host name and IP address. 1320 * System {@linkplain InetAddressResolver resolver} is not used to check 1321 * the validity of the address. 1322 * 1323 * <p> The host name can either be a machine name, such as 1324 * "{@code www.example.com}", or a textual representation of its IP 1325 * address. 1326 * <p> No validity checking is done on the host name either. 1327 * 1328 * <p> If addr specifies an IPv4 address an instance of Inet4Address 1329 * will be returned; otherwise, an instance of Inet6Address 1330 * will be returned. 1331 * 1332 * <p> IPv4 address byte array must be 4 bytes long and IPv6 byte array 1333 * must be 16 bytes long 1334 * 1335 * @param host the specified host 1336 * @param addr the raw IP address in network byte order 1337 * @return an InetAddress object created from the raw IP address. 1338 * @throws UnknownHostException if IP address is of illegal length 1339 * @since 1.4 1340 */ 1341 public static InetAddress getByAddress(String host, byte[] addr) 1342 throws UnknownHostException { 1343 if (host != null && !host.isEmpty() && host.charAt(0) == '[') { 1344 if (host.charAt(host.length()-1) == ']') { 1345 host = host.substring(1, host.length() -1); 1346 } 1347 } 1348 if (addr != null) { 1349 if (addr.length == Inet4Address.INADDRSZ) { 1350 return new Inet4Address(host, addr); 1351 } else if (addr.length == Inet6Address.INADDRSZ) { 1352 byte[] newAddr 1353 = IPAddressUtil.convertFromIPv4MappedAddress(addr); 1354 if (newAddr != null) { 1355 return new Inet4Address(host, newAddr); 1356 } else { 1357 return new Inet6Address(host, addr); 1358 } 1359 } 1360 } 1361 throw new UnknownHostException("addr is of illegal length"); 1362 } 1363 1364 1365 /** 1366 * Determines the IP address of a host, given the host's name. 1367 * 1368 * <p> The host name can either be a machine name, such as 1369 * "{@code www.example.com}", or a textual representation of its 1370 * IP address. If a literal IP address is supplied, only the 1371 * validity of the address format is checked. 1372 * 1373 * <p> For {@code host} specified in literal IPv6 address, 1374 * either the form defined in RFC 2732 or the literal IPv6 address 1375 * format defined in RFC 2373 is accepted. IPv6 scoped addresses are also 1376 * supported. See <a href="Inet6Address.html#scoped">here</a> for a description of IPv6 1377 * scoped addresses. 1378 * 1379 * <p> If the host is {@code null} or {@code host.length()} is equal 1380 * to zero, then an {@code InetAddress} representing an address of the 1381 * loopback interface is returned. 1382 * See <a href="http://www.ietf.org/rfc/rfc3330.txt">RFC 3330</a> 1383 * section 2 and <a href="http://www.ietf.org/rfc/rfc2373.txt">RFC 2373</a> 1384 * section 2.5.3. 1385 * 1386 * <p> If there is a security manager, and {@code host} is not {@code null} 1387 * or {@code host.length() } is not equal to zero, the security manager's 1388 * {@code checkConnect} method is called with the hostname and {@code -1} 1389 * as its arguments to determine if the operation is allowed. 1390 * 1391 * @param host the specified host, or {@code null}. 1392 * @return an IP address for the given host name. 1393 * @throws UnknownHostException if no IP address for the 1394 * {@code host} could be found, or if a scope_id was specified 1395 * for a global IPv6 address. 1396 * @throws SecurityException if a security manager exists 1397 * and its checkConnect method doesn't allow the operation 1398 */ 1399 public static InetAddress getByName(String host) 1400 throws UnknownHostException { 1401 return InetAddress.getAllByName(host)[0]; 1402 } 1403 1404 /** 1405 * Given the name of a host, returns an array of its IP addresses, 1406 * based on the configured system {@linkplain InetAddressResolver resolver}. 1407 * 1408 * <p> The host name can either be a machine name, such as 1409 * "{@code www.example.com}", or a textual representation of its IP 1410 * address. If a literal IP address is supplied, only the 1411 * validity of the address format is checked. 1412 * 1413 * <p> For {@code host} specified in <i>literal IPv6 address</i>, 1414 * either the form defined in RFC 2732 or the literal IPv6 address 1415 * format defined in RFC 2373 is accepted. A literal IPv6 address may 1416 * also be qualified by appending a scoped zone identifier or scope_id. 1417 * The syntax and usage of scope_ids is described 1418 * <a href="Inet6Address.html#scoped">here</a>. 1419 * 1420 * <p> If the host is {@code null} or {@code host.length()} is equal 1421 * to zero, then an {@code InetAddress} representing an address of the 1422 * loopback interface is returned. 1423 * See <a href="http://www.ietf.org/rfc/rfc3330.txt">RFC 3330</a> 1424 * section 2 and <a href="http://www.ietf.org/rfc/rfc2373.txt">RFC 2373</a> 1425 * section 2.5.3. </p> 1426 * 1427 * <p> If there is a security manager, and {@code host} is not {@code null} 1428 * or {@code host.length() } is not equal to zero, the security manager's 1429 * {@code checkConnect} method is called with the hostname and {@code -1} 1430 * as its arguments to determine if the operation is allowed. 1431 * 1432 * @param host the name of the host, or {@code null}. 1433 * @return an array of all the IP addresses for a given host name. 1434 * 1435 * @throws UnknownHostException if no IP address for the 1436 * {@code host} could be found, or if a scope_id was specified 1437 * for a global IPv6 address. 1438 * @throws SecurityException if a security manager exists and its 1439 * {@code checkConnect} method doesn't allow the operation. 1440 * 1441 * @see SecurityManager#checkConnect 1442 */ 1443 public static InetAddress[] getAllByName(String host) 1444 throws UnknownHostException { 1445 1446 if (host == null || host.isEmpty()) { 1447 InetAddress[] ret = new InetAddress[1]; 1448 ret[0] = impl.loopbackAddress(); 1449 return ret; 1450 } 1451 1452 boolean ipv6Expected = false; 1453 if (host.charAt(0) == '[') { 1454 // This is supposed to be an IPv6 literal 1455 if (host.length() > 2 && host.charAt(host.length()-1) == ']') { 1456 host = host.substring(1, host.length() -1); 1457 ipv6Expected = true; 1458 } else { 1459 // This was supposed to be a IPv6 address, but it's not! 1460 throw new UnknownHostException(host + ": invalid IPv6 address"); 1461 } 1462 } 1463 1464 // if host is an IP address, we won't do further lookup 1465 if (Character.digit(host.charAt(0), 16) != -1 1466 || (host.charAt(0) == ':')) { 1467 byte[] addr = null; 1468 int numericZone = -1; 1469 String ifname = null; 1470 // see if it is IPv4 address 1471 addr = IPAddressUtil.textToNumericFormatV4(host); 1472 if (addr == null) { 1473 // This is supposed to be an IPv6 literal 1474 // Check if a numeric or string zone id is present 1475 int pos; 1476 if ((pos=host.indexOf ('%')) != -1) { 1477 numericZone = checkNumericZone (host); 1478 if (numericZone == -1) { /* remainder of string must be an ifname */ 1479 ifname = host.substring (pos+1); 1480 } 1481 } 1482 if ((addr = IPAddressUtil.textToNumericFormatV6(host)) == null && host.contains(":")) { 1483 throw new UnknownHostException(host + ": invalid IPv6 address"); 1484 } 1485 } else if (ipv6Expected) { 1486 // Means an IPv4 literal between brackets! 1487 throw new UnknownHostException("["+host+"]"); 1488 } 1489 InetAddress[] ret = new InetAddress[1]; 1490 if(addr != null) { 1491 if (addr.length == Inet4Address.INADDRSZ) { 1492 ret[0] = new Inet4Address(null, addr); 1493 } else { 1494 if (ifname != null) { 1495 ret[0] = new Inet6Address(null, addr, ifname); 1496 } else { 1497 ret[0] = new Inet6Address(null, addr, numericZone); 1498 } 1499 } 1500 return ret; 1501 } 1502 } else if (ipv6Expected) { 1503 // We were expecting an IPv6 Literal, but got something else 1504 throw new UnknownHostException("["+host+"]"); 1505 } 1506 return getAllByName0(host, true, true); 1507 } 1508 1509 /** 1510 * Returns the loopback address. 1511 * <p> 1512 * The InetAddress returned will represent the IPv4 1513 * loopback address, 127.0.0.1, or the IPv6 loopback 1514 * address, ::1. The IPv4 loopback address returned 1515 * is only one of many in the form 127.*.*.* 1516 * 1517 * @return the InetAddress loopback instance. 1518 * @since 1.7 1519 */ 1520 public static InetAddress getLoopbackAddress() { 1521 return impl.loopbackAddress(); 1522 } 1523 1524 1525 /** 1526 * check if the literal address string has %nn appended 1527 * returns -1 if not, or the numeric value otherwise. 1528 * 1529 * %nn may also be a string that represents the displayName of 1530 * a currently available NetworkInterface. 1531 */ 1532 private static int checkNumericZone (String s) throws UnknownHostException { 1533 int percent = s.indexOf ('%'); 1534 int slen = s.length(); 1535 int digit, zone=0; 1536 if (percent == -1) { 1537 return -1; 1538 } 1539 for (int i=percent+1; i<slen; i++) { 1540 char c = s.charAt(i); 1541 if (c == ']') { 1542 if (i == percent+1) { 1543 /* empty per-cent field */ 1544 return -1; 1545 } 1546 break; 1547 } 1548 if ((digit = Character.digit (c, 10)) < 0) { 1549 return -1; 1550 } 1551 zone = (zone * 10) + digit; 1552 } 1553 return zone; 1554 } 1555 1556 /** 1557 * package private so SocketPermission can call it 1558 */ 1559 static InetAddress[] getAllByName0 (String host, boolean check) 1560 throws UnknownHostException { 1561 return getAllByName0(host, check, true); 1562 } 1563 1564 /** 1565 * Designated lookup method. 1566 * 1567 * @param host host name to look up 1568 * @param check perform security check 1569 * @param useCache use cached value if not expired else always 1570 * perform name service lookup (and cache the result) 1571 * @return array of InetAddress(es) 1572 * @throws UnknownHostException if host name is not found 1573 */ 1574 private static InetAddress[] getAllByName0(String host, 1575 boolean check, 1576 boolean useCache) 1577 throws UnknownHostException { 1578 1579 /* If it gets here it is presumed to be a hostname */ 1580 1581 /* make sure the connection to the host is allowed, before we 1582 * give out a hostname 1583 */ 1584 if (check) { 1585 @SuppressWarnings("removal") 1586 SecurityManager security = System.getSecurityManager(); 1587 if (security != null) { 1588 security.checkConnect(host, -1); 1589 } 1590 } 1591 1592 // remove expired addresses from cache - expirySet keeps them ordered 1593 // by expiry time so we only need to iterate the prefix of the NavigableSet... 1594 long now = System.nanoTime(); 1595 for (CachedAddresses caddrs : expirySet) { 1596 // compare difference of time instants rather than 1597 // time instants directly, to avoid possible overflow. 1598 // (see System.nanoTime() recommendations...) 1599 if ((caddrs.expiryTime - now) < 0L) { 1600 // ConcurrentSkipListSet uses weakly consistent iterator, 1601 // so removing while iterating is OK... 1602 if (expirySet.remove(caddrs)) { 1603 // ... remove from cache 1604 cache.remove(caddrs.host, caddrs); 1605 } 1606 } else { 1607 // we encountered 1st element that expires in future 1608 break; 1609 } 1610 } 1611 1612 // look-up or remove from cache 1613 Addresses addrs; 1614 if (useCache) { 1615 addrs = cache.get(host); 1616 } else { 1617 addrs = cache.remove(host); 1618 if (addrs != null) { 1619 if (addrs instanceof CachedAddresses) { 1620 // try removing from expirySet too if CachedAddresses 1621 expirySet.remove(addrs); 1622 } 1623 addrs = null; 1624 } 1625 } 1626 1627 if (addrs == null) { 1628 // create a NameServiceAddresses instance which will look up 1629 // the name service and install it within cache... 1630 Addresses oldAddrs = cache.putIfAbsent( 1631 host, 1632 addrs = new NameServiceAddresses(host) 1633 ); 1634 if (oldAddrs != null) { // lost putIfAbsent race 1635 addrs = oldAddrs; 1636 } 1637 } 1638 1639 // ask Addresses to get an array of InetAddress(es) and clone it 1640 return addrs.get().clone(); 1641 } 1642 1643 static InetAddress[] getAddressesFromNameService(String host) 1644 throws UnknownHostException { 1645 Stream<InetAddress> addresses = null; 1646 UnknownHostException ex = null; 1647 1648 var resolver = resolver(); 1649 try { 1650 addresses = resolver.lookupAddresses(host, PLATFORM_LOOKUP_POLICY); 1651 } catch (RuntimeException | UnknownHostException x) { 1652 if (host.equalsIgnoreCase("localhost")) { 1653 addresses = Stream.of(impl.loopbackAddress()); 1654 } else if (x instanceof UnknownHostException uhe) { 1655 ex = uhe; 1656 } else { 1657 ex = new UnknownHostException(); 1658 ex.initCause(x); 1659 } 1660 } 1661 1662 if (addresses == null) { 1663 throw ex == null ? new UnknownHostException(host) : ex; 1664 } 1665 return addresses.toArray(InetAddress[]::new); 1666 } 1667 1668 /** 1669 * Returns an {@code InetAddress} object given the raw IP address . 1670 * The argument is in network byte order: the highest order 1671 * byte of the address is in {@code getAddress()[0]}. 1672 * 1673 * <p> This method doesn't block, i.e. no reverse lookup is performed. 1674 * 1675 * <p> IPv4 address byte array must be 4 bytes long and IPv6 byte array 1676 * must be 16 bytes long 1677 * 1678 * @param addr the raw IP address in network byte order 1679 * @return an InetAddress object created from the raw IP address. 1680 * @throws UnknownHostException if IP address is of illegal length 1681 * @since 1.4 1682 */ 1683 public static InetAddress getByAddress(byte[] addr) 1684 throws UnknownHostException { 1685 return getByAddress(null, addr); 1686 } 1687 1688 private static final class CachedLocalHost { 1689 final String host; 1690 final InetAddress addr; 1691 final long expiryTime = System.nanoTime() + 5000_000_000L; // now + 5s; 1692 1693 CachedLocalHost(String host, InetAddress addr) { 1694 this.host = host; 1695 this.addr = addr; 1696 } 1697 } 1698 1699 private static volatile CachedLocalHost cachedLocalHost; 1700 1701 /** 1702 * Returns the address of the local host. This is achieved by retrieving 1703 * the name of the host from the system, then resolving that name into 1704 * an {@code InetAddress}. 1705 * 1706 * <P>Note: The resolved address may be cached for a short period of time. 1707 * </P> 1708 * 1709 * <p>If there is a security manager, its 1710 * {@code checkConnect} method is called 1711 * with the local host name and {@code -1} 1712 * as its arguments to see if the operation is allowed. 1713 * If the operation is not allowed, an InetAddress representing 1714 * the loopback address is returned. 1715 * 1716 * @return the address of the local host. 1717 * 1718 * @throws UnknownHostException if the local host name could not 1719 * be resolved into an address. 1720 * 1721 * @see SecurityManager#checkConnect 1722 * @see java.net.InetAddress#getByName(java.lang.String) 1723 */ 1724 public static InetAddress getLocalHost() throws UnknownHostException { 1725 1726 @SuppressWarnings("removal") 1727 SecurityManager security = System.getSecurityManager(); 1728 try { 1729 // is cached data still valid? 1730 CachedLocalHost clh = cachedLocalHost; 1731 if (clh != null && (clh.expiryTime - System.nanoTime()) >= 0L) { 1732 if (security != null) { 1733 security.checkConnect(clh.host, -1); 1734 } 1735 return clh.addr; 1736 } 1737 1738 String local = impl.getLocalHostName(); 1739 1740 if (security != null) { 1741 security.checkConnect(local, -1); 1742 } 1743 1744 InetAddress localAddr; 1745 if (local.equals("localhost")) { 1746 // shortcut for "localhost" host name 1747 localAddr = impl.loopbackAddress(); 1748 } else { 1749 // call getAllByName0 without security checks and 1750 // without using cached data 1751 try { 1752 localAddr = getAllByName0(local, false, false)[0]; 1753 } catch (UnknownHostException uhe) { 1754 // Rethrow with a more informative error message. 1755 UnknownHostException uhe2 = 1756 new UnknownHostException(local + ": " + 1757 uhe.getMessage()); 1758 uhe2.initCause(uhe); 1759 throw uhe2; 1760 } 1761 } 1762 cachedLocalHost = new CachedLocalHost(local, localAddr); 1763 return localAddr; 1764 } catch (java.lang.SecurityException e) { 1765 return impl.loopbackAddress(); 1766 } 1767 } 1768 1769 /** 1770 * Perform class load-time initializations. 1771 */ 1772 private static native void init(); 1773 1774 1775 /* 1776 * Returns the InetAddress representing anyLocalAddress 1777 * (typically 0.0.0.0 or ::0) 1778 */ 1779 static InetAddress anyLocalAddress() { 1780 return impl.anyLocalAddress(); 1781 } 1782 1783 /** 1784 * Initializes an empty InetAddress. 1785 */ 1786 @java.io.Serial 1787 private void readObjectNoData () { 1788 if (getClass().getClassLoader() != null) { 1789 throw new SecurityException ("invalid address type"); 1790 } 1791 } 1792 1793 private static final jdk.internal.misc.Unsafe UNSAFE 1794 = jdk.internal.misc.Unsafe.getUnsafe(); 1795 private static final long FIELDS_OFFSET 1796 = UNSAFE.objectFieldOffset(InetAddress.class, "holder"); 1797 1798 /** 1799 * Restores the state of this object from the stream. 1800 * 1801 * @param s the {@code ObjectInputStream} from which data is read 1802 * @throws IOException if an I/O error occurs 1803 * @throws ClassNotFoundException if a serialized class cannot be loaded 1804 */ 1805 @java.io.Serial 1806 private void readObject (ObjectInputStream s) throws 1807 IOException, ClassNotFoundException { 1808 if (getClass().getClassLoader() != null) { 1809 throw new SecurityException ("invalid address type"); 1810 } 1811 GetField gf = s.readFields(); 1812 String host = (String)gf.get("hostName", null); 1813 int address = gf.get("address", 0); 1814 int family = gf.get("family", 0); 1815 if (family != IPv4 && family != IPv6) { 1816 throw new InvalidObjectException("invalid address family type: " + family); 1817 } 1818 InetAddressHolder h = new InetAddressHolder(host, address, family); 1819 UNSAFE.putReference(this, FIELDS_OFFSET, h); 1820 } 1821 1822 /* needed because the serializable fields no longer exist */ 1823 1824 /** 1825 * @serialField hostName String the hostname for this address 1826 * @serialField address int holds a 32-bit IPv4 address. 1827 * @serialField family int specifies the address family type, for instance, 1828 * {@code '1'} for IPv4 addresses, and {@code '2'} for IPv6 addresses. 1829 */ 1830 @java.io.Serial 1831 private static final ObjectStreamField[] serialPersistentFields = { 1832 new ObjectStreamField("hostName", String.class), 1833 new ObjectStreamField("address", int.class), 1834 new ObjectStreamField("family", int.class), 1835 }; 1836 1837 /** 1838 * Writes the state of this object to the stream. 1839 * 1840 * @param s the {@code ObjectOutputStream} to which data is written 1841 * @throws IOException if an I/O error occurs 1842 */ 1843 @java.io.Serial 1844 private void writeObject (ObjectOutputStream s) throws 1845 IOException { 1846 if (getClass().getClassLoader() != null) { 1847 throw new SecurityException ("invalid address type"); 1848 } 1849 PutField pf = s.putFields(); 1850 pf.put("hostName", holder().getHostName()); 1851 pf.put("address", holder().getAddress()); 1852 pf.put("family", holder().getFamily()); 1853 s.writeFields(); 1854 } 1855 } 1856 1857 /* 1858 * Simple factory to create the impl 1859 */ 1860 class InetAddressImplFactory { 1861 1862 static InetAddressImpl create() { 1863 return isIPv6Supported() ? 1864 new Inet6AddressImpl() : new Inet4AddressImpl(); 1865 } 1866 1867 static native boolean isIPv6Supported(); 1868 }