Coverage Summary for Class: InetAddresses (com.google.common.net)

Class Method, % Line, %
InetAddresses 0% (0/43) 0% (0/308)
InetAddresses$TeredoInfo 0% (0/5) 0% (0/11)
Total 0% (0/48) 0% (0/319)


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