001/* 002 * Copyright (C) 2008 The Guava Authors 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 005 * in compliance with the License. You may obtain a copy of the License at 006 * 007 * http://www.apache.org/licenses/LICENSE-2.0 008 * 009 * Unless required by applicable law or agreed to in writing, software distributed under the License 010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 011 * or implied. See the License for the specific language governing permissions and limitations under 012 * the License. 013 */ 014 015package com.google.common.net; 016 017import static com.google.common.base.Preconditions.checkArgument; 018import static com.google.common.base.Preconditions.checkNotNull; 019import static java.lang.Math.max; 020import static java.util.Objects.requireNonNull; 021 022import com.google.common.annotations.GwtIncompatible; 023import com.google.common.annotations.J2ktIncompatible; 024import com.google.common.base.CharMatcher; 025import com.google.common.base.MoreObjects; 026import com.google.common.hash.Hashing; 027import com.google.common.io.ByteStreams; 028import com.google.common.primitives.Ints; 029import com.google.errorprone.annotations.CanIgnoreReturnValue; 030import java.math.BigInteger; 031import java.net.Inet4Address; 032import java.net.Inet6Address; 033import java.net.InetAddress; 034import java.net.NetworkInterface; 035import java.net.SocketException; 036import java.net.UnknownHostException; 037import java.nio.ByteBuffer; 038import java.util.Arrays; 039import java.util.Locale; 040import org.jspecify.annotations.Nullable; 041 042/** 043 * Static utility methods pertaining to {@link InetAddress} instances. 044 * 045 * <p><b>Important note:</b> Unlike {@code InetAddress.getByName()}, the methods of this class never 046 * cause DNS services to be accessed. For this reason, you should prefer these methods as much as 047 * possible over their JDK equivalents whenever you are expecting to handle only IP address string 048 * literals -- there is no blocking DNS penalty for a malformed string. 049 * 050 * <p>When dealing with {@link Inet4Address} and {@link Inet6Address} objects as byte arrays (vis. 051 * {@code InetAddress.getAddress()}) they are 4 and 16 bytes in length, respectively, and represent 052 * the address in network byte order. 053 * 054 * <p>Examples of IP addresses and their byte representations: 055 * 056 * <dl> 057 * <dt>The IPv4 loopback address, {@code "127.0.0.1"}. 058 * <dd>{@code 7f 00 00 01} 059 * <dt>The IPv6 loopback address, {@code "::1"}. 060 * <dd>{@code 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01} 061 * <dt>From the IPv6 reserved documentation prefix ({@code 2001:db8::/32}), {@code "2001:db8::1"}. 062 * <dd>{@code 20 01 0d b8 00 00 00 00 00 00 00 00 00 00 00 01} 063 * <dt>An IPv6 "IPv4 compatible" (or "compat") address, {@code "::192.168.0.1"}. 064 * <dd>{@code 00 00 00 00 00 00 00 00 00 00 00 00 c0 a8 00 01} 065 * <dt>An IPv6 "IPv4 mapped" address, {@code "::ffff:192.168.0.1"}. 066 * <dd>{@code 00 00 00 00 00 00 00 00 00 00 ff ff c0 a8 00 01} 067 * </dl> 068 * 069 * <p>A few notes about IPv6 "IPv4 mapped" addresses and their observed use in Java. 070 * 071 * <p>"IPv4 mapped" addresses were originally a representation of IPv4 addresses for use on an IPv6 072 * socket that could receive both IPv4 and IPv6 connections (by disabling the {@code IPV6_V6ONLY} 073 * socket option on an IPv6 socket). Yes, it's confusing. Nevertheless, these "mapped" addresses 074 * were never supposed to be seen on the wire. That assumption was dropped, some say mistakenly, in 075 * later RFCs with the apparent aim of making IPv4-to-IPv6 transition simpler. 076 * 077 * <p>Technically one <i>can</i> create a 128bit IPv6 address with the wire format of a "mapped" 078 * address, as shown above, and transmit it in an IPv6 packet header. However, Java's InetAddress 079 * creation methods appear to adhere doggedly to the original intent of the "mapped" address: all 080 * "mapped" addresses return {@link Inet4Address} objects. 081 * 082 * <p>For added safety, it is common for IPv6 network operators to filter all packets where either 083 * the source or destination address appears to be a "compat" or "mapped" address. Filtering 084 * suggestions usually recommend discarding any packets with source or destination addresses in the 085 * invalid range {@code ::/3}, which includes both of these bizarre address formats. For more 086 * information on "bogons", including lists of IPv6 bogon space, see: 087 * 088 * <ul> 089 * <li><a target="_parent" 090 * href="http://en.wikipedia.org/wiki/Bogon_filtering">http://en.wikipedia. 091 * org/wiki/Bogon_filtering</a> 092 * <li><a target="_parent" 093 * href="http://www.cymru.com/Bogons/ipv6.txt">http://www.cymru.com/Bogons/ ipv6.txt</a> 094 * <li><a target="_parent" href="http://www.cymru.com/Bogons/v6bogon.html">http://www.cymru.com/ 095 * Bogons/v6bogon.html</a> 096 * <li><a target="_parent" href="http://www.space.net/~gert/RIPE/ipv6-filters.html">http://www. 097 * space.net/~gert/RIPE/ipv6-filters.html</a> 098 * </ul> 099 * 100 * @author Erik Kline 101 * @since 5.0 102 */ 103@J2ktIncompatible 104@GwtIncompatible 105public final class InetAddresses { 106 private static final int IPV4_PART_COUNT = 4; 107 private static final int IPV6_PART_COUNT = 8; 108 private static final char IPV4_DELIMITER = '.'; 109 private static final char IPV6_DELIMITER = ':'; 110 private static final CharMatcher IPV4_DELIMITER_MATCHER = CharMatcher.is(IPV4_DELIMITER); 111 private static final CharMatcher IPV6_DELIMITER_MATCHER = CharMatcher.is(IPV6_DELIMITER); 112 private static final Inet4Address LOOPBACK4 = (Inet4Address) forString("127.0.0.1"); 113 private static final Inet4Address ANY4 = (Inet4Address) forString("0.0.0.0"); 114 115 private InetAddresses() {} 116 117 /** 118 * Returns an {@link Inet4Address}, given a byte array representation of the IPv4 address. 119 * 120 * @param bytes byte array representing an IPv4 address (should be of length 4) 121 * @return {@link Inet4Address} corresponding to the supplied byte array 122 * @throws IllegalArgumentException if a valid {@link Inet4Address} can not be created 123 */ 124 private static Inet4Address getInet4Address(byte[] bytes) { 125 checkArgument( 126 bytes.length == 4, 127 "Byte array has invalid length for an IPv4 address: %s != 4.", 128 bytes.length); 129 130 // Given a 4-byte array, this cast should always succeed. 131 return (Inet4Address) bytesToInetAddress(bytes, null); 132 } 133 134 /** 135 * Returns the {@link InetAddress} having the given string representation. 136 * 137 * <p>This deliberately avoids all nameservice lookups (e.g. no DNS). 138 * 139 * <p>This method accepts non-ASCII digits, for example {@code "192.168.0.1"} (those are fullwidth 140 * characters). That is consistent with {@link InetAddress}, but not with various RFCs. If you 141 * want to accept ASCII digits only, you can use something like {@code 142 * CharMatcher.ascii().matchesAllOf(ipString)}. 143 * 144 * <p>The scope ID is validated against the interfaces on the machine, which requires permissions 145 * under Android. 146 * 147 * <p><b>Android users on API >= 29:</b> Prefer {@code InetAddresses.parseNumericAddress}. 148 * 149 * @param ipString {@code String} containing an IPv4 or IPv6 string literal, e.g. {@code 150 * "192.168.0.1"} or {@code "2001:db8::1"} or with a scope ID, e.g. {@code "2001:db8::1%eth0"} 151 * @return {@link InetAddress} representing the argument 152 * @throws IllegalArgumentException if the argument is not a valid IP string literal or if the 153 * address has a scope ID that fails validation against the interfaces on the machine (as 154 * required by Java's {@link InetAddress}) 155 */ 156 @CanIgnoreReturnValue // TODO(b/219820829): consider removing 157 public static InetAddress forString(String ipString) { 158 Scope scope = new Scope(); 159 byte[] addr = ipStringToBytes(ipString, scope); 160 161 // The argument was malformed, i.e. not an IP string literal. 162 if (addr == null) { 163 throw formatIllegalArgumentException("'%s' is not an IP string literal.", ipString); 164 } 165 166 return bytesToInetAddress(addr, scope.scope); 167 } 168 169 /** 170 * Returns {@code true} if the supplied string is a valid IP string literal, {@code false} 171 * otherwise. 172 * 173 * <p>This method accepts non-ASCII digits, for example {@code "192.168.0.1"} (those are fullwidth 174 * characters). That is consistent with {@link InetAddress}, but not with various RFCs. If you 175 * want to accept ASCII digits only, you can use something like {@code 176 * CharMatcher.ascii().matchesAllOf(ipString)}. 177 * 178 * <p>Note that if this method returns {@code true}, a call to {@link #forString(String)} can 179 * still throw if the address has a scope ID that fails validation against the interfaces on the 180 * machine. 181 * 182 * @param ipString {@code String} to evaluated as an IP string literal 183 * @return {@code true} if the argument is a valid IP string literal 184 */ 185 public static boolean isInetAddress(String ipString) { 186 return ipStringToBytes(ipString, null) != null; 187 } 188 189 private static final class Scope { 190 private String scope; 191 } 192 193 /** Returns {@code null} if unable to parse into a {@code byte[]}. */ 194 private static byte @Nullable [] ipStringToBytes(String ipStringParam, @Nullable Scope scope) { 195 String ipString = ipStringParam; 196 // Make a first pass to categorize the characters in this string. 197 boolean hasColon = false; 198 boolean hasDot = false; 199 int percentIndex = -1; 200 for (int i = 0; i < ipString.length(); i++) { 201 char c = ipString.charAt(i); 202 if (c == '.') { 203 hasDot = true; 204 } else if (c == ':') { 205 if (hasDot) { 206 return null; // Colons must not appear after dots. 207 } 208 hasColon = true; 209 } else if (c == '%') { 210 percentIndex = i; 211 break; 212 } else if (Character.digit(c, 16) == -1) { 213 return null; // Everything else must be a decimal or hex digit. 214 } 215 } 216 217 // Now decide which address family to parse. 218 if (hasColon) { 219 if (hasDot) { 220 ipString = convertDottedQuadToHex(ipString); 221 if (ipString == null) { 222 return null; 223 } 224 } 225 if (percentIndex != -1) { 226 if (scope != null) { 227 scope.scope = ipString.substring(percentIndex + 1); 228 } 229 ipString = ipString.substring(0, percentIndex); 230 } 231 return textToNumericFormatV6(ipString); 232 } else if (hasDot) { 233 if (percentIndex != -1) { 234 return null; // Scope IDs are not supported for IPV4 235 } 236 return textToNumericFormatV4(ipString); 237 } 238 return null; 239 } 240 241 private static byte @Nullable [] textToNumericFormatV4(String ipString) { 242 if (IPV4_DELIMITER_MATCHER.countIn(ipString) + 1 != IPV4_PART_COUNT) { 243 return null; // Wrong number of parts 244 } 245 246 byte[] bytes = new byte[IPV4_PART_COUNT]; 247 int start = 0; 248 // Iterate through the parts of the ip string. 249 // Invariant: start is always the beginning of an octet. 250 for (int i = 0; i < IPV4_PART_COUNT; i++) { 251 int end = ipString.indexOf(IPV4_DELIMITER, start); 252 if (end == -1) { 253 end = ipString.length(); 254 } 255 try { 256 bytes[i] = parseOctet(ipString, start, end); 257 } catch (NumberFormatException ex) { 258 return null; 259 } 260 start = end + 1; 261 } 262 263 return bytes; 264 } 265 266 private static byte @Nullable [] textToNumericFormatV6(String ipString) { 267 // An address can have [2..8] colons. 268 int delimiterCount = IPV6_DELIMITER_MATCHER.countIn(ipString); 269 if (delimiterCount < 2 || delimiterCount > IPV6_PART_COUNT) { 270 return null; 271 } 272 int partsSkipped = IPV6_PART_COUNT - (delimiterCount + 1); // estimate; may be modified later 273 boolean hasSkip = false; 274 // Scan for the appearance of ::, to mark a skip-format IPV6 string and adjust the partsSkipped 275 // estimate. 276 for (int i = 0; i < ipString.length() - 1; i++) { 277 if (ipString.charAt(i) == IPV6_DELIMITER && ipString.charAt(i + 1) == IPV6_DELIMITER) { 278 if (hasSkip) { 279 return null; // Can't have more than one :: 280 } 281 hasSkip = true; 282 partsSkipped++; // :: means we skipped an extra part in between the two delimiters. 283 if (i == 0) { 284 partsSkipped++; // Begins with ::, so we skipped the part preceding the first : 285 } 286 if (i == ipString.length() - 2) { 287 partsSkipped++; // Ends with ::, so we skipped the part after the last : 288 } 289 } 290 } 291 if (ipString.charAt(0) == IPV6_DELIMITER && ipString.charAt(1) != IPV6_DELIMITER) { 292 return null; // ^: requires ^:: 293 } 294 if (ipString.charAt(ipString.length() - 1) == IPV6_DELIMITER 295 && ipString.charAt(ipString.length() - 2) != IPV6_DELIMITER) { 296 return null; // :$ requires ::$ 297 } 298 if (hasSkip && partsSkipped <= 0) { 299 return null; // :: must expand to at least one '0' 300 } 301 if (!hasSkip && delimiterCount + 1 != IPV6_PART_COUNT) { 302 return null; // Incorrect number of parts 303 } 304 305 ByteBuffer rawBytes = ByteBuffer.allocate(2 * IPV6_PART_COUNT); 306 try { 307 // Iterate through the parts of the ip string. 308 // Invariant: start is always the beginning of a hextet, or the second ':' of the skip 309 // sequence "::" 310 int start = 0; 311 if (ipString.charAt(0) == IPV6_DELIMITER) { 312 start = 1; 313 } 314 while (start < ipString.length()) { 315 int end = ipString.indexOf(IPV6_DELIMITER, start); 316 if (end == -1) { 317 end = ipString.length(); 318 } 319 if (ipString.charAt(start) == IPV6_DELIMITER) { 320 // expand zeroes 321 for (int i = 0; i < partsSkipped; i++) { 322 rawBytes.putShort((short) 0); 323 } 324 325 } else { 326 rawBytes.putShort(parseHextet(ipString, start, end)); 327 } 328 start = end + 1; 329 } 330 } catch (NumberFormatException ex) { 331 return null; 332 } 333 return rawBytes.array(); 334 } 335 336 private static @Nullable String convertDottedQuadToHex(String ipString) { 337 int lastColon = ipString.lastIndexOf(':'); 338 String initialPart = ipString.substring(0, lastColon + 1); 339 String dottedQuad = ipString.substring(lastColon + 1); 340 byte[] quad = textToNumericFormatV4(dottedQuad); 341 if (quad == null) { 342 return null; 343 } 344 String penultimate = Integer.toHexString(((quad[0] & 0xff) << 8) | (quad[1] & 0xff)); 345 String ultimate = Integer.toHexString(((quad[2] & 0xff) << 8) | (quad[3] & 0xff)); 346 return initialPart + penultimate + ":" + ultimate; 347 } 348 349 private static byte parseOctet(String ipString, int start, int end) { 350 // Note: we already verified that this string contains only hex digits, but the string may still 351 // contain non-decimal characters. 352 int length = end - start; 353 if (length <= 0 || length > 3) { 354 throw new NumberFormatException(); 355 } 356 // Disallow leading zeroes, because no clear standard exists on 357 // whether these should be interpreted as decimal or octal. 358 if (length > 1 && ipString.charAt(start) == '0') { 359 throw new NumberFormatException(); 360 } 361 int octet = 0; 362 for (int i = start; i < end; i++) { 363 octet *= 10; 364 int digit = Character.digit(ipString.charAt(i), 10); 365 if (digit < 0) { 366 throw new NumberFormatException(); 367 } 368 octet += digit; 369 } 370 if (octet > 255) { 371 throw new NumberFormatException(); 372 } 373 return (byte) octet; 374 } 375 376 /** Returns a -1 if unable to parse */ 377 private static int tryParseDecimal(String string, int start, int end) { 378 int decimal = 0; 379 final int max = Integer.MAX_VALUE / 10; // for int overflow detection 380 for (int i = start; i < end; i++) { 381 if (decimal > max) { 382 return -1; 383 } 384 decimal *= 10; 385 int digit = Character.digit(string.charAt(i), 10); 386 if (digit < 0) { 387 return -1; 388 } 389 decimal += digit; 390 } 391 return decimal; 392 } 393 394 // Parse a hextet out of the ipString from start (inclusive) to end (exclusive) 395 private static short parseHextet(String ipString, int start, int end) { 396 // Note: we already verified that this string contains only hex digits. 397 int length = end - start; 398 if (length <= 0 || length > 4) { 399 throw new NumberFormatException(); 400 } 401 int hextet = 0; 402 for (int i = start; i < end; i++) { 403 hextet = hextet << 4; 404 hextet |= Character.digit(ipString.charAt(i), 16); 405 } 406 return (short) hextet; 407 } 408 409 /** 410 * Convert a byte array into an InetAddress. 411 * 412 * <p>{@link InetAddress#getByAddress} is documented as throwing a checked exception "if IP 413 * address is of illegal length." We replace it with an unchecked exception, for use by callers 414 * who already know that addr is an array of length 4 or 16. 415 * 416 * @param addr the raw 4-byte or 16-byte IP address in big-endian order 417 * @return an InetAddress object created from the raw IP address 418 */ 419 private static InetAddress bytesToInetAddress(byte[] addr, @Nullable String scope) { 420 try { 421 InetAddress address = InetAddress.getByAddress(addr); 422 if (scope == null) { 423 return address; 424 } 425 checkArgument( 426 address instanceof Inet6Address, "Unexpected state, scope should only appear for ipv6"); 427 Inet6Address v6Address = (Inet6Address) address; 428 int interfaceIndex = tryParseDecimal(scope, 0, scope.length()); 429 if (interfaceIndex != -1) { 430 return Inet6Address.getByAddress( 431 v6Address.getHostAddress(), v6Address.getAddress(), interfaceIndex); 432 } 433 try { 434 NetworkInterface asInterface = NetworkInterface.getByName(scope); 435 if (asInterface == null) { 436 throw formatIllegalArgumentException("No such interface: '%s'", scope); 437 } 438 return Inet6Address.getByAddress( 439 v6Address.getHostAddress(), v6Address.getAddress(), asInterface); 440 } catch (SocketException | UnknownHostException e) { 441 throw new IllegalArgumentException("No such interface: " + scope, e); 442 } 443 } catch (UnknownHostException e) { 444 throw new AssertionError(e); 445 } 446 } 447 448 /** 449 * Returns the string representation of an {@link InetAddress}. 450 * 451 * <p>For IPv4 addresses, this is identical to {@link InetAddress#getHostAddress()}, but for IPv6 452 * addresses, the output follows <a href="http://tools.ietf.org/html/rfc5952">RFC 5952</a> section 453 * 4. The main difference is that this method uses "::" for zero compression, while Java's version 454 * uses the uncompressed form (except on Android, where the zero compression is also done). The 455 * other difference is that this method outputs any scope ID in the format that it was provided at 456 * creation time, while Android may always output it as an interface name, even if it was supplied 457 * as a numeric ID. 458 * 459 * <p>This method uses hexadecimal for all IPv6 addresses, including IPv4-mapped IPv6 addresses 460 * such as "::c000:201". 461 * 462 * @param ip {@link InetAddress} to be converted to an address string 463 * @return {@code String} containing the text-formatted IP address 464 * @since 10.0 465 */ 466 public static String toAddrString(InetAddress ip) { 467 checkNotNull(ip); 468 if (ip instanceof Inet4Address) { 469 // For IPv4, Java's formatting is good enough. 470 // requireNonNull accommodates Android's @RecentlyNullable annotation on getHostAddress 471 return requireNonNull(ip.getHostAddress()); 472 } 473 byte[] bytes = ip.getAddress(); 474 int[] hextets = new int[IPV6_PART_COUNT]; 475 for (int i = 0; i < hextets.length; i++) { 476 hextets[i] = Ints.fromBytes((byte) 0, (byte) 0, bytes[2 * i], bytes[2 * i + 1]); 477 } 478 compressLongestRunOfZeroes(hextets); 479 480 return hextetsToIPv6String(hextets) + scopeWithDelimiter((Inet6Address) ip); 481 } 482 483 private static String scopeWithDelimiter(Inet6Address ip) { 484 // getHostAddress on android sometimes maps the scope ID to an invalid interface name; if the 485 // mapped interface isn't present, fallback to use the scope ID (which has no validation against 486 // present interfaces) 487 NetworkInterface scopedInterface = ip.getScopedInterface(); 488 if (scopedInterface != null) { 489 return "%" + scopedInterface.getName(); 490 } 491 int scope = ip.getScopeId(); 492 if (scope != 0) { 493 return "%" + scope; 494 } 495 return ""; 496 } 497 498 /** 499 * Identify and mark the longest run of zeroes in an IPv6 address. 500 * 501 * <p>Only runs of two or more hextets are considered. In case of a tie, the leftmost run wins. If 502 * a qualifying run is found, its hextets are replaced by the sentinel value -1. 503 * 504 * @param hextets {@code int[]} mutable array of eight 16-bit hextets 505 */ 506 private static void compressLongestRunOfZeroes(int[] hextets) { 507 int bestRunStart = -1; 508 int bestRunLength = -1; 509 int runStart = -1; 510 for (int i = 0; i < hextets.length + 1; i++) { 511 if (i < hextets.length && hextets[i] == 0) { 512 if (runStart < 0) { 513 runStart = i; 514 } 515 } else if (runStart >= 0) { 516 int runLength = i - runStart; 517 if (runLength > bestRunLength) { 518 bestRunStart = runStart; 519 bestRunLength = runLength; 520 } 521 runStart = -1; 522 } 523 } 524 if (bestRunLength >= 2) { 525 Arrays.fill(hextets, bestRunStart, bestRunStart + bestRunLength, -1); 526 } 527 } 528 529 /** 530 * Convert a list of hextets into a human-readable IPv6 address. 531 * 532 * <p>In order for "::" compression to work, the input should contain negative sentinel values in 533 * place of the elided zeroes. 534 * 535 * @param hextets {@code int[]} array of eight 16-bit hextets, or -1s 536 */ 537 private static String hextetsToIPv6String(int[] hextets) { 538 // While scanning the array, handle these state transitions: 539 // start->num => "num" start->gap => "::" 540 // num->num => ":num" num->gap => "::" 541 // gap->num => "num" gap->gap => "" 542 StringBuilder buf = new StringBuilder(39); 543 boolean lastWasNumber = false; 544 for (int i = 0; i < hextets.length; i++) { 545 boolean thisIsNumber = hextets[i] >= 0; 546 if (thisIsNumber) { 547 if (lastWasNumber) { 548 buf.append(':'); 549 } 550 buf.append(Integer.toHexString(hextets[i])); 551 } else { 552 if (i == 0 || lastWasNumber) { 553 buf.append("::"); 554 } 555 } 556 lastWasNumber = thisIsNumber; 557 } 558 return buf.toString(); 559 } 560 561 /** 562 * Returns the string representation of an {@link InetAddress} suitable for inclusion in a URI. 563 * 564 * <p>For IPv4 addresses, this is identical to {@link InetAddress#getHostAddress()}, but for IPv6 565 * addresses it compresses zeroes and surrounds the text with square brackets; for example {@code 566 * "[2001:db8::1]"}. 567 * 568 * <p>Per section 3.2.2 of <a target="_parent" 569 * href="http://tools.ietf.org/html/rfc3986#section-3.2.2">RFC 3986</a>, a URI containing an IPv6 570 * string literal is of the form {@code "http://[2001:db8::1]:8888/index.html"}. 571 * 572 * <p>Use of either {@link InetAddresses#toAddrString}, {@link InetAddress#getHostAddress()}, or 573 * this method is recommended over {@link InetAddress#toString()} when an IP address string 574 * literal is desired. This is because {@link InetAddress#toString()} prints the hostname and the 575 * IP address string joined by a "/". 576 * 577 * @param ip {@link InetAddress} to be converted to URI string literal 578 * @return {@code String} containing URI-safe string literal 579 */ 580 public static String toUriString(InetAddress ip) { 581 if (ip instanceof Inet6Address) { 582 return "[" + toAddrString(ip) + "]"; 583 } 584 return toAddrString(ip); 585 } 586 587 /** 588 * Returns an InetAddress representing the literal IPv4 or IPv6 host portion of a URL, encoded in 589 * the format specified by RFC 3986 section 3.2.2. 590 * 591 * <p>This method is similar to {@link InetAddresses#forString(String)}, however, it requires that 592 * IPv6 addresses are surrounded by square brackets. 593 * 594 * <p>This method is the inverse of {@link InetAddresses#toUriString(java.net.InetAddress)}. 595 * 596 * <p>This method accepts non-ASCII digits, for example {@code "192.168.0.1"} (those are fullwidth 597 * characters). That is consistent with {@link InetAddress}, but not with various RFCs. If you 598 * want to accept ASCII digits only, you can use something like {@code 599 * CharMatcher.ascii().matchesAllOf(ipString)}. 600 * 601 * @param hostAddr an RFC 3986 section 3.2.2 encoded IPv4 or IPv6 address 602 * @return an InetAddress representing the address in {@code hostAddr} 603 * @throws IllegalArgumentException if {@code hostAddr} is not a valid IPv4 address, or IPv6 604 * address surrounded by square brackets, or if the address has a scope ID that fails 605 * validation against the interfaces on the machine (as required by Java's {@link 606 * InetAddress}) 607 */ 608 public static InetAddress forUriString(String hostAddr) { 609 InetAddress addr = forUriStringOrNull(hostAddr, /* parseScope= */ true); 610 if (addr == null) { 611 throw formatIllegalArgumentException("Not a valid URI IP literal: '%s'", hostAddr); 612 } 613 614 return addr; 615 } 616 617 private static @Nullable InetAddress forUriStringOrNull(String hostAddr, boolean parseScope) { 618 checkNotNull(hostAddr); 619 620 // Decide if this should be an IPv6 or IPv4 address. 621 String ipString; 622 int expectBytes; 623 if (hostAddr.startsWith("[") && hostAddr.endsWith("]")) { 624 ipString = hostAddr.substring(1, hostAddr.length() - 1); 625 expectBytes = 16; 626 } else { 627 ipString = hostAddr; 628 expectBytes = 4; 629 } 630 631 // Parse the address, and make sure the length/version is correct. 632 Scope scope = parseScope ? new Scope() : null; 633 byte[] addr = ipStringToBytes(ipString, scope); 634 if (addr == null || addr.length != expectBytes) { 635 return null; 636 } 637 638 return bytesToInetAddress(addr, (scope != null) ? scope.scope : null); 639 } 640 641 /** 642 * Returns {@code true} if the supplied string is a valid URI IP string literal, {@code false} 643 * otherwise. 644 * 645 * <p>This method accepts non-ASCII digits, for example {@code "192.168.0.1"} (those are fullwidth 646 * characters). That is consistent with {@link InetAddress}, but not with various RFCs. If you 647 * want to accept ASCII digits only, you can use something like {@code 648 * CharMatcher.ascii().matchesAllOf(ipString)}. 649 * 650 * <p>Note that if this method returns {@code true}, a call to {@link #forUriString(String)} can 651 * still throw if the address has a scope ID that fails validation against the interfaces on the 652 * machine. 653 * 654 * @param ipString {@code String} to evaluated as an IP URI host string literal 655 * @return {@code true} if the argument is a valid IP URI host 656 */ 657 public static boolean isUriInetAddress(String ipString) { 658 return forUriStringOrNull(ipString, /* parseScope= */ false) != null; 659 } 660 661 /** 662 * Evaluates whether the argument is an IPv6 "compat" address. 663 * 664 * <p>An "IPv4 compatible", or "compat", address is one with 96 leading bits of zero, with the 665 * remaining 32 bits interpreted as an IPv4 address. These are conventionally represented in 666 * string literals as {@code "::192.168.0.1"}, though {@code "::c0a8:1"} is also considered an 667 * IPv4 compatible address (and equivalent to {@code "::192.168.0.1"}). 668 * 669 * <p>For more on IPv4 compatible addresses see section 2.5.5.1 of <a target="_parent" 670 * href="http://tools.ietf.org/html/rfc4291#section-2.5.5.1">RFC 4291</a>. 671 * 672 * <p>NOTE: This method is different from {@link Inet6Address#isIPv4CompatibleAddress} in that it 673 * more correctly classifies {@code "::"} and {@code "::1"} as proper IPv6 addresses (which they 674 * are), NOT IPv4 compatible addresses (which they are generally NOT considered to be). 675 * 676 * @param ip {@link Inet6Address} to be examined for embedded IPv4 compatible address format 677 * @return {@code true} if the argument is a valid "compat" address 678 */ 679 public static boolean isCompatIPv4Address(Inet6Address ip) { 680 if (!ip.isIPv4CompatibleAddress()) { 681 return false; 682 } 683 684 byte[] bytes = ip.getAddress(); 685 if ((bytes[12] == 0) 686 && (bytes[13] == 0) 687 && (bytes[14] == 0) 688 && ((bytes[15] == 0) || (bytes[15] == 1))) { 689 return false; 690 } 691 692 return true; 693 } 694 695 /** 696 * Returns the IPv4 address embedded in an IPv4 compatible address. 697 * 698 * @param ip {@link Inet6Address} to be examined for an embedded IPv4 address 699 * @return {@link Inet4Address} of the embedded IPv4 address 700 * @throws IllegalArgumentException if the argument is not a valid IPv4 compatible address 701 */ 702 public static Inet4Address getCompatIPv4Address(Inet6Address ip) { 703 checkArgument( 704 isCompatIPv4Address(ip), "Address '%s' is not IPv4-compatible.", toAddrString(ip)); 705 706 return getInet4Address(Arrays.copyOfRange(ip.getAddress(), 12, 16)); 707 } 708 709 /** 710 * Evaluates whether the argument is a 6to4 address. 711 * 712 * <p>6to4 addresses begin with the {@code "2002::/16"} prefix. The next 32 bits are the IPv4 713 * address of the host to which IPv6-in-IPv4 tunneled packets should be routed. 714 * 715 * <p>For more on 6to4 addresses see section 2 of <a target="_parent" 716 * href="http://tools.ietf.org/html/rfc3056#section-2">RFC 3056</a>. 717 * 718 * @param ip {@link Inet6Address} to be examined for 6to4 address format 719 * @return {@code true} if the argument is a 6to4 address 720 */ 721 public static boolean is6to4Address(Inet6Address ip) { 722 byte[] bytes = ip.getAddress(); 723 return (bytes[0] == (byte) 0x20) && (bytes[1] == (byte) 0x02); 724 } 725 726 /** 727 * Returns the IPv4 address embedded in a 6to4 address. 728 * 729 * @param ip {@link Inet6Address} to be examined for embedded IPv4 in 6to4 address 730 * @return {@link Inet4Address} of embedded IPv4 in 6to4 address 731 * @throws IllegalArgumentException if the argument is not a valid IPv6 6to4 address 732 */ 733 public static Inet4Address get6to4IPv4Address(Inet6Address ip) { 734 checkArgument(is6to4Address(ip), "Address '%s' is not a 6to4 address.", toAddrString(ip)); 735 736 return getInet4Address(Arrays.copyOfRange(ip.getAddress(), 2, 6)); 737 } 738 739 /** 740 * A simple immutable data class to encapsulate the information to be found in a Teredo address. 741 * 742 * <p>All of the fields in this class are encoded in various portions of the IPv6 address as part 743 * of the protocol. More protocols details can be found at: <a target="_parent" 744 * href="http://en.wikipedia.org/wiki/Teredo_tunneling">http://en.wikipedia. 745 * org/wiki/Teredo_tunneling</a>. 746 * 747 * <p>The RFC can be found here: <a target="_parent" href="http://tools.ietf.org/html/rfc4380">RFC 748 * 4380</a>. 749 * 750 * @since 5.0 751 */ 752 public static final class TeredoInfo { 753 private final Inet4Address server; 754 private final Inet4Address client; 755 private final int port; 756 private final int flags; 757 758 /** 759 * Constructs a TeredoInfo instance. 760 * 761 * <p>Both server and client can be {@code null}, in which case the value {@code "0.0.0.0"} will 762 * be assumed. 763 * 764 * @throws IllegalArgumentException if either of the {@code port} or the {@code flags} arguments 765 * are out of range of an unsigned short 766 */ 767 // TODO: why is this public? 768 public TeredoInfo( 769 @Nullable Inet4Address server, @Nullable Inet4Address client, int port, int flags) { 770 checkArgument( 771 (port >= 0) && (port <= 0xffff), "port '%s' is out of range (0 <= port <= 0xffff)", port); 772 checkArgument( 773 (flags >= 0) && (flags <= 0xffff), 774 "flags '%s' is out of range (0 <= flags <= 0xffff)", 775 flags); 776 777 this.server = MoreObjects.firstNonNull(server, ANY4); 778 this.client = MoreObjects.firstNonNull(client, ANY4); 779 this.port = port; 780 this.flags = flags; 781 } 782 783 public Inet4Address getServer() { 784 return server; 785 } 786 787 public Inet4Address getClient() { 788 return client; 789 } 790 791 public int getPort() { 792 return port; 793 } 794 795 public int getFlags() { 796 return flags; 797 } 798 } 799 800 /** 801 * Evaluates whether the argument is a Teredo address. 802 * 803 * <p>Teredo addresses begin with the {@code "2001::/32"} prefix. 804 * 805 * @param ip {@link Inet6Address} to be examined for Teredo address format 806 * @return {@code true} if the argument is a Teredo address 807 */ 808 public static boolean isTeredoAddress(Inet6Address ip) { 809 byte[] bytes = ip.getAddress(); 810 return (bytes[0] == (byte) 0x20) 811 && (bytes[1] == (byte) 0x01) 812 && (bytes[2] == 0) 813 && (bytes[3] == 0); 814 } 815 816 /** 817 * Returns the Teredo information embedded in a Teredo address. 818 * 819 * @param ip {@link Inet6Address} to be examined for embedded Teredo information 820 * @return extracted {@code TeredoInfo} 821 * @throws IllegalArgumentException if the argument is not a valid IPv6 Teredo address 822 */ 823 public static TeredoInfo getTeredoInfo(Inet6Address ip) { 824 checkArgument(isTeredoAddress(ip), "Address '%s' is not a Teredo address.", toAddrString(ip)); 825 826 byte[] bytes = ip.getAddress(); 827 Inet4Address server = getInet4Address(Arrays.copyOfRange(bytes, 4, 8)); 828 829 int flags = ByteStreams.newDataInput(bytes, 8).readShort() & 0xffff; 830 831 // Teredo obfuscates the mapped client port, per section 4 of the RFC. 832 int port = ~ByteStreams.newDataInput(bytes, 10).readShort() & 0xffff; 833 834 byte[] clientBytes = Arrays.copyOfRange(bytes, 12, 16); 835 for (int i = 0; i < clientBytes.length; i++) { 836 // Teredo obfuscates the mapped client IP, per section 4 of the RFC. 837 clientBytes[i] = (byte) ~clientBytes[i]; 838 } 839 Inet4Address client = getInet4Address(clientBytes); 840 841 return new TeredoInfo(server, client, port, flags); 842 } 843 844 /** 845 * Evaluates whether the argument is an ISATAP address. 846 * 847 * <p>From RFC 5214: "ISATAP interface identifiers are constructed in Modified EUI-64 format [...] 848 * by concatenating the 24-bit IANA OUI (00-00-5E), the 8-bit hexadecimal value 0xFE, and a 32-bit 849 * IPv4 address in network byte order [...]" 850 * 851 * <p>For more on ISATAP addresses see section 6.1 of <a target="_parent" 852 * href="http://tools.ietf.org/html/rfc5214#section-6.1">RFC 5214</a>. 853 * 854 * @param ip {@link Inet6Address} to be examined for ISATAP address format 855 * @return {@code true} if the argument is an ISATAP address 856 */ 857 public static boolean isIsatapAddress(Inet6Address ip) { 858 859 // If it's a Teredo address with the right port (41217, or 0xa101) 860 // which would be encoded as 0x5efe then it can't be an ISATAP address. 861 if (isTeredoAddress(ip)) { 862 return false; 863 } 864 865 byte[] bytes = ip.getAddress(); 866 867 if ((bytes[8] | (byte) 0x03) != (byte) 0x03) { 868 869 // Verify that high byte of the 64 bit identifier is zero, modulo 870 // the U/L and G bits, with which we are not concerned. 871 return false; 872 } 873 874 return (bytes[9] == (byte) 0x00) && (bytes[10] == (byte) 0x5e) && (bytes[11] == (byte) 0xfe); 875 } 876 877 /** 878 * Returns the IPv4 address embedded in an ISATAP address. 879 * 880 * @param ip {@link Inet6Address} to be examined for embedded IPv4 in ISATAP address 881 * @return {@link Inet4Address} of embedded IPv4 in an ISATAP address 882 * @throws IllegalArgumentException if the argument is not a valid IPv6 ISATAP address 883 */ 884 public static Inet4Address getIsatapIPv4Address(Inet6Address ip) { 885 checkArgument(isIsatapAddress(ip), "Address '%s' is not an ISATAP address.", toAddrString(ip)); 886 887 return getInet4Address(Arrays.copyOfRange(ip.getAddress(), 12, 16)); 888 } 889 890 /** 891 * Examines the Inet6Address to determine if it is an IPv6 address of one of the specified address 892 * types that contain an embedded IPv4 address. 893 * 894 * <p>NOTE: ISATAP addresses are explicitly excluded from this method due to their trivial 895 * spoofability. With other transition addresses spoofing involves (at least) infection of one's 896 * BGP routing table. 897 * 898 * @param ip {@link Inet6Address} to be examined for embedded IPv4 client address 899 * @return {@code true} if there is an embedded IPv4 client address 900 * @since 7.0 901 */ 902 public static boolean hasEmbeddedIPv4ClientAddress(Inet6Address ip) { 903 return isCompatIPv4Address(ip) || is6to4Address(ip) || isTeredoAddress(ip); 904 } 905 906 /** 907 * Examines the Inet6Address to extract the embedded IPv4 client address if the InetAddress is an 908 * IPv6 address of one of the specified address types that contain an embedded IPv4 address. 909 * 910 * <p>NOTE: ISATAP addresses are explicitly excluded from this method due to their trivial 911 * spoofability. With other transition addresses spoofing involves (at least) infection of one's 912 * BGP routing table. 913 * 914 * @param ip {@link Inet6Address} to be examined for embedded IPv4 client address 915 * @return {@link Inet4Address} of embedded IPv4 client address 916 * @throws IllegalArgumentException if the argument does not have a valid embedded IPv4 address 917 */ 918 public static Inet4Address getEmbeddedIPv4ClientAddress(Inet6Address ip) { 919 if (isCompatIPv4Address(ip)) { 920 return getCompatIPv4Address(ip); 921 } 922 923 if (is6to4Address(ip)) { 924 return get6to4IPv4Address(ip); 925 } 926 927 if (isTeredoAddress(ip)) { 928 return getTeredoInfo(ip).getClient(); 929 } 930 931 throw formatIllegalArgumentException("'%s' has no embedded IPv4 address.", toAddrString(ip)); 932 } 933 934 /** 935 * Evaluates whether the argument is an "IPv4 mapped" IPv6 address. 936 * 937 * <p>An "IPv4 mapped" address is anything in the range ::ffff:0:0/96 (sometimes written as 938 * ::ffff:0.0.0.0/96), with the last 32 bits interpreted as an IPv4 address. 939 * 940 * <p>For more on IPv4 mapped addresses see section 2.5.5.2 of <a target="_parent" 941 * href="http://tools.ietf.org/html/rfc4291#section-2.5.5.2">RFC 4291</a>. 942 * 943 * <p>Note: This method takes a {@code String} argument because {@link InetAddress} automatically 944 * collapses mapped addresses to IPv4. (It is actually possible to avoid this using one of the 945 * obscure {@link Inet6Address} methods, but it would be unwise to depend on such a 946 * poorly-documented feature.) 947 * 948 * <p>This method accepts non-ASCII digits. That is consistent with {@link InetAddress}, but not 949 * with various RFCs. If you want to accept ASCII digits only, you can use something like {@code 950 * CharMatcher.ascii().matchesAllOf(ipString)}. 951 * 952 * @param ipString {@code String} to be examined for embedded IPv4-mapped IPv6 address format 953 * @return {@code true} if the argument is a valid "mapped" address 954 * @since 10.0 955 */ 956 public static boolean isMappedIPv4Address(String ipString) { 957 byte[] bytes = ipStringToBytes(ipString, null); 958 if (bytes != null && bytes.length == 16) { 959 for (int i = 0; i < 10; i++) { 960 if (bytes[i] != 0) { 961 return false; 962 } 963 } 964 for (int i = 10; i < 12; i++) { 965 if (bytes[i] != (byte) 0xff) { 966 return false; 967 } 968 } 969 return true; 970 } 971 return false; 972 } 973 974 /** 975 * Coerces an IPv6 address into an IPv4 address. 976 * 977 * <p>HACK: As long as applications continue to use IPv4 addresses for indexing into tables, 978 * accounting, et cetera, it may be necessary to <b>coerce</b> IPv6 addresses into IPv4 addresses. 979 * This method does so by hashing 64 bits of the IPv6 address into {@code 224.0.0.0/3} (64 bits 980 * into 29 bits): 981 * 982 * <ul> 983 * <li>If the IPv6 address contains an embedded IPv4 address, the function hashes that. 984 * <li>Otherwise, it hashes the upper 64 bits of the IPv6 address. 985 * </ul> 986 * 987 * <p>A "coerced" IPv4 address is equivalent to itself. 988 * 989 * <p>NOTE: This method is failsafe for security purposes: ALL IPv6 addresses (except localhost 990 * (::1)) are hashed to avoid the security risk associated with extracting an embedded IPv4 991 * address that might permit elevated privileges. 992 * 993 * @param ip {@link InetAddress} to "coerce" 994 * @return {@link Inet4Address} represented "coerced" address 995 * @since 7.0 996 */ 997 public static Inet4Address getCoercedIPv4Address(InetAddress ip) { 998 if (ip instanceof Inet4Address) { 999 return (Inet4Address) ip; 1000 } 1001 1002 // Special cases: 1003 byte[] bytes = ip.getAddress(); 1004 boolean leadingBytesOfZero = true; 1005 for (int i = 0; i < 15; ++i) { 1006 if (bytes[i] != 0) { 1007 leadingBytesOfZero = false; 1008 break; 1009 } 1010 } 1011 if (leadingBytesOfZero && (bytes[15] == 1)) { 1012 return LOOPBACK4; // ::1 1013 } else if (leadingBytesOfZero && (bytes[15] == 0)) { 1014 return ANY4; // ::0 1015 } 1016 1017 Inet6Address ip6 = (Inet6Address) ip; 1018 long addressAsLong = 0; 1019 if (hasEmbeddedIPv4ClientAddress(ip6)) { 1020 addressAsLong = getEmbeddedIPv4ClientAddress(ip6).hashCode(); 1021 } else { 1022 // Just extract the high 64 bits (assuming the rest is user-modifiable). 1023 addressAsLong = ByteBuffer.wrap(ip6.getAddress(), 0, 8).getLong(); 1024 } 1025 1026 // Many strategies for hashing are possible. This might suffice for now. 1027 int coercedHash = Hashing.murmur3_32_fixed().hashLong(addressAsLong).asInt(); 1028 1029 // Squash into 224/4 Multicast and 240/4 Reserved space (i.e. 224/3). 1030 coercedHash |= 0xe0000000; 1031 1032 // Fixup to avoid some "illegal" values. Currently the only potential 1033 // illegal value is 255.255.255.255. 1034 if (coercedHash == 0xffffffff) { 1035 coercedHash = 0xfffffffe; 1036 } 1037 1038 return getInet4Address(Ints.toByteArray(coercedHash)); 1039 } 1040 1041 /** 1042 * Returns an integer representing an IPv4 address regardless of whether the supplied argument is 1043 * an IPv4 address or not. 1044 * 1045 * <p>IPv6 addresses are <b>coerced</b> to IPv4 addresses before being converted to integers. 1046 * 1047 * <p>As long as there are applications that assume that all IP addresses are IPv4 addresses and 1048 * can therefore be converted safely to integers (for whatever purpose) this function can be used 1049 * to handle IPv6 addresses as well until the application is suitably fixed. 1050 * 1051 * <p>NOTE: an IPv6 address coerced to an IPv4 address can only be used for such purposes as 1052 * rudimentary identification or indexing into a collection of real {@link InetAddress}es. They 1053 * cannot be used as real addresses for the purposes of network communication. 1054 * 1055 * @param ip {@link InetAddress} to convert 1056 * @return {@code int}, "coerced" if ip is not an IPv4 address 1057 * @since 7.0 1058 */ 1059 public static int coerceToInteger(InetAddress ip) { 1060 return ByteStreams.newDataInput(getCoercedIPv4Address(ip).getAddress()).readInt(); 1061 } 1062 1063 /** 1064 * Returns a BigInteger representing the address. 1065 * 1066 * <p>Unlike {@code coerceToInteger}, IPv6 addresses are not coerced to IPv4 addresses. 1067 * 1068 * @param address {@link InetAddress} to convert 1069 * @return {@code BigInteger} representation of the address 1070 * @since 28.2 1071 */ 1072 public static BigInteger toBigInteger(InetAddress address) { 1073 return new BigInteger(1, address.getAddress()); 1074 } 1075 1076 /** 1077 * Returns an Inet4Address having the integer value specified by the argument. 1078 * 1079 * @param address {@code int}, the 32bit integer address to be converted 1080 * @return {@link Inet4Address} equivalent of the argument 1081 */ 1082 public static Inet4Address fromInteger(int address) { 1083 return getInet4Address(Ints.toByteArray(address)); 1084 } 1085 1086 /** 1087 * Returns the {@code Inet4Address} corresponding to a given {@code BigInteger}. 1088 * 1089 * @param address BigInteger representing the IPv4 address 1090 * @return Inet4Address representation of the given BigInteger 1091 * @throws IllegalArgumentException if the BigInteger is not between 0 and 2^32-1 1092 * @since 28.2 1093 */ 1094 public static Inet4Address fromIPv4BigInteger(BigInteger address) { 1095 return (Inet4Address) fromBigInteger(address, false); 1096 } 1097 /** 1098 * Returns the {@code Inet6Address} corresponding to a given {@code BigInteger}. 1099 * 1100 * @param address BigInteger representing the IPv6 address 1101 * @return Inet6Address representation of the given BigInteger 1102 * @throws IllegalArgumentException if the BigInteger is not between 0 and 2^128-1 1103 * @since 28.2 1104 */ 1105 public static Inet6Address fromIPv6BigInteger(BigInteger address) { 1106 return (Inet6Address) fromBigInteger(address, true); 1107 } 1108 1109 /** 1110 * Converts a BigInteger to either an IPv4 or IPv6 address. If the IP is IPv4, it must be 1111 * constrained to 32 bits, otherwise it is constrained to 128 bits. 1112 * 1113 * @param address the address represented as a big integer 1114 * @param isIpv6 whether the created address should be IPv4 or IPv6 1115 * @return the BigInteger converted to an address 1116 * @throws IllegalArgumentException if the BigInteger is not between 0 and maximum value for IPv4 1117 * or IPv6 respectively 1118 */ 1119 private static InetAddress fromBigInteger(BigInteger address, boolean isIpv6) { 1120 checkArgument(address.signum() >= 0, "BigInteger must be greater than or equal to 0"); 1121 1122 int numBytes = isIpv6 ? 16 : 4; 1123 1124 byte[] addressBytes = address.toByteArray(); 1125 byte[] targetCopyArray = new byte[numBytes]; 1126 1127 int srcPos = max(0, addressBytes.length - numBytes); 1128 int copyLength = addressBytes.length - srcPos; 1129 int destPos = numBytes - copyLength; 1130 1131 // Check the extra bytes in the BigInteger are all zero. 1132 for (int i = 0; i < srcPos; i++) { 1133 if (addressBytes[i] != 0x00) { 1134 throw formatIllegalArgumentException( 1135 "BigInteger cannot be converted to InetAddress because it has more than %d" 1136 + " bytes: %s", 1137 numBytes, address); 1138 } 1139 } 1140 1141 // Copy the bytes into the least significant positions. 1142 System.arraycopy(addressBytes, srcPos, targetCopyArray, destPos, copyLength); 1143 1144 try { 1145 return InetAddress.getByAddress(targetCopyArray); 1146 } catch (UnknownHostException impossible) { 1147 throw new AssertionError(impossible); 1148 } 1149 } 1150 1151 /** 1152 * Returns an address from a <b>little-endian ordered</b> byte array (the opposite of what {@link 1153 * InetAddress#getByAddress} expects). 1154 * 1155 * <p>IPv4 address byte array must be 4 bytes long and IPv6 byte array must be 16 bytes long. 1156 * 1157 * @param addr the raw IP address in little-endian byte order 1158 * @return an InetAddress object created from the raw IP address 1159 * @throws UnknownHostException if IP address is of illegal length 1160 */ 1161 public static InetAddress fromLittleEndianByteArray(byte[] addr) throws UnknownHostException { 1162 byte[] reversed = new byte[addr.length]; 1163 for (int i = 0; i < addr.length; i++) { 1164 reversed[i] = addr[addr.length - i - 1]; 1165 } 1166 return InetAddress.getByAddress(reversed); 1167 } 1168 1169 /** 1170 * Returns a new InetAddress that is one less than the passed in address. This method works for 1171 * both IPv4 and IPv6 addresses. 1172 * 1173 * @param address the InetAddress to decrement 1174 * @return a new InetAddress that is one less than the passed in address 1175 * @throws IllegalArgumentException if InetAddress is at the beginning of its range 1176 * @since 18.0 1177 */ 1178 public static InetAddress decrement(InetAddress address) { 1179 byte[] addr = address.getAddress(); 1180 int i = addr.length - 1; 1181 while (i >= 0 && addr[i] == (byte) 0x00) { 1182 addr[i] = (byte) 0xff; 1183 i--; 1184 } 1185 1186 checkArgument(i >= 0, "Decrementing %s would wrap.", address); 1187 1188 addr[i]--; 1189 return bytesToInetAddress(addr, null); 1190 } 1191 1192 /** 1193 * Returns a new InetAddress that is one more than the passed in address. This method works for 1194 * both IPv4 and IPv6 addresses. 1195 * 1196 * @param address the InetAddress to increment 1197 * @return a new InetAddress that is one more than the passed in address 1198 * @throws IllegalArgumentException if InetAddress is at the end of its range 1199 * @since 10.0 1200 */ 1201 public static InetAddress increment(InetAddress address) { 1202 byte[] addr = address.getAddress(); 1203 int i = addr.length - 1; 1204 while (i >= 0 && addr[i] == (byte) 0xff) { 1205 addr[i] = 0; 1206 i--; 1207 } 1208 1209 checkArgument(i >= 0, "Incrementing %s would wrap.", address); 1210 1211 addr[i]++; 1212 return bytesToInetAddress(addr, null); 1213 } 1214 1215 /** 1216 * Returns true if the InetAddress is either 255.255.255.255 for IPv4 or 1217 * ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff for IPv6. 1218 * 1219 * @return true if the InetAddress is either 255.255.255.255 for IPv4 or 1220 * ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff for IPv6 1221 * @since 10.0 1222 */ 1223 public static boolean isMaximum(InetAddress address) { 1224 byte[] addr = address.getAddress(); 1225 for (byte b : addr) { 1226 if (b != (byte) 0xff) { 1227 return false; 1228 } 1229 } 1230 return true; 1231 } 1232 1233 private static IllegalArgumentException formatIllegalArgumentException( 1234 String format, Object... args) { 1235 return new IllegalArgumentException(String.format(Locale.ROOT, format, args)); 1236 } 1237}