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; 019 020import com.google.common.annotations.Beta; 021import com.google.common.annotations.GwtIncompatible; 022import com.google.common.base.MoreObjects; 023import com.google.common.base.Splitter; 024import com.google.common.hash.Hashing; 025import com.google.common.io.ByteStreams; 026import com.google.common.primitives.Ints; 027import java.net.Inet4Address; 028import java.net.Inet6Address; 029import java.net.InetAddress; 030import java.net.UnknownHostException; 031import java.nio.ByteBuffer; 032import java.util.Arrays; 033import java.util.Locale; 034import org.checkerframework.checker.nullness.compatqual.NullableDecl; 035 036/** 037 * Static utility methods pertaining to {@link InetAddress} instances. 038 * 039 * <p><b>Important note:</b> Unlike {@code InetAddress.getByName()}, the methods of this class never 040 * cause DNS services to be accessed. For this reason, you should prefer these methods as much as 041 * possible over their JDK equivalents whenever you are expecting to handle only IP address string 042 * literals -- there is no blocking DNS penalty for a malformed string. 043 * 044 * <p>When dealing with {@link Inet4Address} and {@link Inet6Address} objects as byte arrays (vis. 045 * {@code InetAddress.getAddress()}) they are 4 and 16 bytes in length, respectively, and represent 046 * the address in network byte order. 047 * 048 * <p>Examples of IP addresses and their byte representations: 049 * 050 * <dl> 051 * <dt>The IPv4 loopback address, {@code "127.0.0.1"}. 052 * <dd>{@code 7f 00 00 01} 053 * <dt>The IPv6 loopback address, {@code "::1"}. 054 * <dd>{@code 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01} 055 * <dt>From the IPv6 reserved documentation prefix ({@code 2001:db8::/32}), {@code "2001:db8::1"}. 056 * <dd>{@code 20 01 0d b8 00 00 00 00 00 00 00 00 00 00 00 01} 057 * <dt>An IPv6 "IPv4 compatible" (or "compat") address, {@code "::192.168.0.1"}. 058 * <dd>{@code 00 00 00 00 00 00 00 00 00 00 00 00 c0 a8 00 01} 059 * <dt>An IPv6 "IPv4 mapped" address, {@code "::ffff:192.168.0.1"}. 060 * <dd>{@code 00 00 00 00 00 00 00 00 00 00 ff ff c0 a8 00 01} 061 * </dl> 062 * 063 * <p>A few notes about IPv6 "IPv4 mapped" addresses and their observed use in Java. 064 * 065 * <p>"IPv4 mapped" addresses were originally a representation of IPv4 addresses for use on an IPv6 066 * socket that could receive both IPv4 and IPv6 connections (by disabling the {@code IPV6_V6ONLY} 067 * socket option on an IPv6 socket). Yes, it's confusing. Nevertheless, these "mapped" addresses 068 * were never supposed to be seen on the wire. That assumption was dropped, some say mistakenly, in 069 * later RFCs with the apparent aim of making IPv4-to-IPv6 transition simpler. 070 * 071 * <p>Technically one <i>can</i> create a 128bit IPv6 address with the wire format of a "mapped" 072 * address, as shown above, and transmit it in an IPv6 packet header. However, Java's InetAddress 073 * creation methods appear to adhere doggedly to the original intent of the "mapped" address: all 074 * "mapped" addresses return {@link Inet4Address} objects. 075 * 076 * <p>For added safety, it is common for IPv6 network operators to filter all packets where either 077 * the source or destination address appears to be a "compat" or "mapped" address. Filtering 078 * suggestions usually recommend discarding any packets with source or destination addresses in the 079 * invalid range {@code ::/3}, which includes both of these bizarre address formats. For more 080 * information on "bogons", including lists of IPv6 bogon space, see: 081 * 082 * <ul> 083 * <li><a target="_parent" 084 * href="http://en.wikipedia.org/wiki/Bogon_filtering">http://en.wikipedia. 085 * org/wiki/Bogon_filtering</a> 086 * <li><a target="_parent" 087 * href="http://www.cymru.com/Bogons/ipv6.txt">http://www.cymru.com/Bogons/ ipv6.txt</a> 088 * <li><a target="_parent" href="http://www.cymru.com/Bogons/v6bogon.html">http://www.cymru.com/ 089 * Bogons/v6bogon.html</a> 090 * <li><a target="_parent" href="http://www.space.net/~gert/RIPE/ipv6-filters.html">http://www. 091 * space.net/~gert/RIPE/ipv6-filters.html</a> 092 * </ul> 093 * 094 * @author Erik Kline 095 * @since 5.0 096 */ 097@Beta 098@GwtIncompatible 099public final class InetAddresses { 100 private static final int IPV4_PART_COUNT = 4; 101 private static final int IPV6_PART_COUNT = 8; 102 private static final Splitter IPV4_SPLITTER = Splitter.on('.').limit(IPV4_PART_COUNT); 103 private static final Inet4Address LOOPBACK4 = (Inet4Address) forString("127.0.0.1"); 104 private static final Inet4Address ANY4 = (Inet4Address) forString("0.0.0.0"); 105 106 private InetAddresses() {} 107 108 /** 109 * Returns an {@link Inet4Address}, given a byte array representation of the IPv4 address. 110 * 111 * @param bytes byte array representing an IPv4 address (should be of length 4) 112 * @return {@link Inet4Address} corresponding to the supplied byte array 113 * @throws IllegalArgumentException if a valid {@link Inet4Address} can not be created 114 */ 115 private static Inet4Address getInet4Address(byte[] bytes) { 116 checkArgument( 117 bytes.length == 4, 118 "Byte array has invalid length for an IPv4 address: %s != 4.", 119 bytes.length); 120 121 // Given a 4-byte array, this cast should always succeed. 122 return (Inet4Address) bytesToInetAddress(bytes); 123 } 124 125 /** 126 * Returns the {@link InetAddress} having the given string representation. 127 * 128 * <p>This deliberately avoids all nameservice lookups (e.g. no DNS). 129 * 130 * @param ipString {@code String} containing an IPv4 or IPv6 string literal, e.g. {@code 131 * "192.168.0.1"} or {@code "2001:db8::1"} 132 * @return {@link InetAddress} representing the argument 133 * @throws IllegalArgumentException if the argument is not a valid IP string literal 134 */ 135 public static InetAddress forString(String ipString) { 136 byte[] addr = ipStringToBytes(ipString); 137 138 // The argument was malformed, i.e. not an IP string literal. 139 if (addr == null) { 140 throw formatIllegalArgumentException("'%s' is not an IP string literal.", ipString); 141 } 142 143 return bytesToInetAddress(addr); 144 } 145 146 /** 147 * Returns {@code true} if the supplied string is a valid IP string literal, {@code false} 148 * otherwise. 149 * 150 * @param ipString {@code String} to evaluated as an IP string literal 151 * @return {@code true} if the argument is a valid IP string literal 152 */ 153 public static boolean isInetAddress(String ipString) { 154 return ipStringToBytes(ipString) != null; 155 } 156 157 @NullableDecl 158 private static byte[] ipStringToBytes(String ipString) { 159 // Make a first pass to categorize the characters in this string. 160 boolean hasColon = false; 161 boolean hasDot = false; 162 for (int i = 0; i < ipString.length(); i++) { 163 char c = ipString.charAt(i); 164 if (c == '.') { 165 hasDot = true; 166 } else if (c == ':') { 167 if (hasDot) { 168 return null; // Colons must not appear after dots. 169 } 170 hasColon = true; 171 } else if (Character.digit(c, 16) == -1) { 172 return null; // Everything else must be a decimal or hex digit. 173 } 174 } 175 176 // Now decide which address family to parse. 177 if (hasColon) { 178 if (hasDot) { 179 ipString = convertDottedQuadToHex(ipString); 180 if (ipString == null) { 181 return null; 182 } 183 } 184 return textToNumericFormatV6(ipString); 185 } else if (hasDot) { 186 return textToNumericFormatV4(ipString); 187 } 188 return null; 189 } 190 191 @NullableDecl 192 private static byte[] textToNumericFormatV4(String ipString) { 193 byte[] bytes = new byte[IPV4_PART_COUNT]; 194 int i = 0; 195 try { 196 for (String octet : IPV4_SPLITTER.split(ipString)) { 197 bytes[i++] = parseOctet(octet); 198 } 199 } catch (NumberFormatException ex) { 200 return null; 201 } 202 203 return i == IPV4_PART_COUNT ? bytes : null; 204 } 205 206 @NullableDecl 207 private static byte[] textToNumericFormatV6(String ipString) { 208 // An address can have [2..8] colons, and N colons make N+1 parts. 209 String[] parts = ipString.split(":", IPV6_PART_COUNT + 2); 210 if (parts.length < 3 || parts.length > IPV6_PART_COUNT + 1) { 211 return null; 212 } 213 214 // Disregarding the endpoints, find "::" with nothing in between. 215 // This indicates that a run of zeroes has been skipped. 216 int skipIndex = -1; 217 for (int i = 1; i < parts.length - 1; i++) { 218 if (parts[i].length() == 0) { 219 if (skipIndex >= 0) { 220 return null; // Can't have more than one :: 221 } 222 skipIndex = i; 223 } 224 } 225 226 int partsHi; // Number of parts to copy from above/before the "::" 227 int partsLo; // Number of parts to copy from below/after the "::" 228 if (skipIndex >= 0) { 229 // If we found a "::", then check if it also covers the endpoints. 230 partsHi = skipIndex; 231 partsLo = parts.length - skipIndex - 1; 232 if (parts[0].length() == 0 && --partsHi != 0) { 233 return null; // ^: requires ^:: 234 } 235 if (parts[parts.length - 1].length() == 0 && --partsLo != 0) { 236 return null; // :$ requires ::$ 237 } 238 } else { 239 // Otherwise, allocate the entire address to partsHi. The endpoints 240 // could still be empty, but parseHextet() will check for that. 241 partsHi = parts.length; 242 partsLo = 0; 243 } 244 245 // If we found a ::, then we must have skipped at least one part. 246 // Otherwise, we must have exactly the right number of parts. 247 int partsSkipped = IPV6_PART_COUNT - (partsHi + partsLo); 248 if (!(skipIndex >= 0 ? partsSkipped >= 1 : partsSkipped == 0)) { 249 return null; 250 } 251 252 // Now parse the hextets into a byte array. 253 ByteBuffer rawBytes = ByteBuffer.allocate(2 * IPV6_PART_COUNT); 254 try { 255 for (int i = 0; i < partsHi; i++) { 256 rawBytes.putShort(parseHextet(parts[i])); 257 } 258 for (int i = 0; i < partsSkipped; i++) { 259 rawBytes.putShort((short) 0); 260 } 261 for (int i = partsLo; i > 0; i--) { 262 rawBytes.putShort(parseHextet(parts[parts.length - i])); 263 } 264 } catch (NumberFormatException ex) { 265 return null; 266 } 267 return rawBytes.array(); 268 } 269 270 @NullableDecl 271 private static String convertDottedQuadToHex(String ipString) { 272 int lastColon = ipString.lastIndexOf(':'); 273 String initialPart = ipString.substring(0, lastColon + 1); 274 String dottedQuad = ipString.substring(lastColon + 1); 275 byte[] quad = textToNumericFormatV4(dottedQuad); 276 if (quad == null) { 277 return null; 278 } 279 String penultimate = Integer.toHexString(((quad[0] & 0xff) << 8) | (quad[1] & 0xff)); 280 String ultimate = Integer.toHexString(((quad[2] & 0xff) << 8) | (quad[3] & 0xff)); 281 return initialPart + penultimate + ":" + ultimate; 282 } 283 284 private static byte parseOctet(String ipPart) { 285 // Note: we already verified that this string contains only hex digits. 286 int octet = Integer.parseInt(ipPart); 287 // Disallow leading zeroes, because no clear standard exists on 288 // whether these should be interpreted as decimal or octal. 289 if (octet > 255 || (ipPart.startsWith("0") && ipPart.length() > 1)) { 290 throw new NumberFormatException(); 291 } 292 return (byte) octet; 293 } 294 295 private static short parseHextet(String ipPart) { 296 // Note: we already verified that this string contains only hex digits. 297 int hextet = Integer.parseInt(ipPart, 16); 298 if (hextet > 0xffff) { 299 throw new NumberFormatException(); 300 } 301 return (short) hextet; 302 } 303 304 /** 305 * Convert a byte array into an InetAddress. 306 * 307 * <p>{@link InetAddress#getByAddress} is documented as throwing a checked exception "if IP 308 * address is of illegal length." We replace it with an unchecked exception, for use by callers 309 * who already know that addr is an array of length 4 or 16. 310 * 311 * @param addr the raw 4-byte or 16-byte IP address in big-endian order 312 * @return an InetAddress object created from the raw IP address 313 */ 314 private static InetAddress bytesToInetAddress(byte[] addr) { 315 try { 316 return InetAddress.getByAddress(addr); 317 } catch (UnknownHostException e) { 318 throw new AssertionError(e); 319 } 320 } 321 322 /** 323 * Returns the string representation of an {@link InetAddress}. 324 * 325 * <p>For IPv4 addresses, this is identical to {@link InetAddress#getHostAddress()}, but for IPv6 326 * addresses, the output follows <a href="http://tools.ietf.org/html/rfc5952">RFC 5952</a> section 327 * 4. The main difference is that this method uses "::" for zero compression, while Java's version 328 * uses the uncompressed form. 329 * 330 * <p>This method uses hexadecimal for all IPv6 addresses, including IPv4-mapped IPv6 addresses 331 * such as "::c000:201". The output does not include a Scope ID. 332 * 333 * @param ip {@link InetAddress} to be converted to an address string 334 * @return {@code String} containing the text-formatted IP address 335 * @since 10.0 336 */ 337 public static String toAddrString(InetAddress ip) { 338 checkNotNull(ip); 339 if (ip instanceof Inet4Address) { 340 // For IPv4, Java's formatting is good enough. 341 return ip.getHostAddress(); 342 } 343 checkArgument(ip instanceof Inet6Address); 344 byte[] bytes = ip.getAddress(); 345 int[] hextets = new int[IPV6_PART_COUNT]; 346 for (int i = 0; i < hextets.length; i++) { 347 hextets[i] = Ints.fromBytes((byte) 0, (byte) 0, bytes[2 * i], bytes[2 * i + 1]); 348 } 349 compressLongestRunOfZeroes(hextets); 350 return hextetsToIPv6String(hextets); 351 } 352 353 /** 354 * Identify and mark the longest run of zeroes in an IPv6 address. 355 * 356 * <p>Only runs of two or more hextets are considered. In case of a tie, the leftmost run wins. If 357 * a qualifying run is found, its hextets are replaced by the sentinel value -1. 358 * 359 * @param hextets {@code int[]} mutable array of eight 16-bit hextets 360 */ 361 private static void compressLongestRunOfZeroes(int[] hextets) { 362 int bestRunStart = -1; 363 int bestRunLength = -1; 364 int runStart = -1; 365 for (int i = 0; i < hextets.length + 1; i++) { 366 if (i < hextets.length && hextets[i] == 0) { 367 if (runStart < 0) { 368 runStart = i; 369 } 370 } else if (runStart >= 0) { 371 int runLength = i - runStart; 372 if (runLength > bestRunLength) { 373 bestRunStart = runStart; 374 bestRunLength = runLength; 375 } 376 runStart = -1; 377 } 378 } 379 if (bestRunLength >= 2) { 380 Arrays.fill(hextets, bestRunStart, bestRunStart + bestRunLength, -1); 381 } 382 } 383 384 /** 385 * Convert a list of hextets into a human-readable IPv6 address. 386 * 387 * <p>In order for "::" compression to work, the input should contain negative sentinel values in 388 * place of the elided zeroes. 389 * 390 * @param hextets {@code int[]} array of eight 16-bit hextets, or -1s 391 */ 392 private static String hextetsToIPv6String(int[] hextets) { 393 // While scanning the array, handle these state transitions: 394 // start->num => "num" start->gap => "::" 395 // num->num => ":num" num->gap => "::" 396 // gap->num => "num" gap->gap => "" 397 StringBuilder buf = new StringBuilder(39); 398 boolean lastWasNumber = false; 399 for (int i = 0; i < hextets.length; i++) { 400 boolean thisIsNumber = hextets[i] >= 0; 401 if (thisIsNumber) { 402 if (lastWasNumber) { 403 buf.append(':'); 404 } 405 buf.append(Integer.toHexString(hextets[i])); 406 } else { 407 if (i == 0 || lastWasNumber) { 408 buf.append("::"); 409 } 410 } 411 lastWasNumber = thisIsNumber; 412 } 413 return buf.toString(); 414 } 415 416 /** 417 * Returns the string representation of an {@link InetAddress} suitable for inclusion in a URI. 418 * 419 * <p>For IPv4 addresses, this is identical to {@link InetAddress#getHostAddress()}, but for IPv6 420 * addresses it compresses zeroes and surrounds the text with square brackets; for example {@code 421 * "[2001:db8::1]"}. 422 * 423 * <p>Per section 3.2.2 of <a target="_parent" 424 * href="http://tools.ietf.org/html/rfc3986#section-3.2.2">RFC 3986</a>, a URI containing an IPv6 425 * string literal is of the form {@code "http://[2001:db8::1]:8888/index.html"}. 426 * 427 * <p>Use of either {@link InetAddresses#toAddrString}, {@link InetAddress#getHostAddress()}, or 428 * this method is recommended over {@link InetAddress#toString()} when an IP address string 429 * literal is desired. This is because {@link InetAddress#toString()} prints the hostname and the 430 * IP address string joined by a "/". 431 * 432 * @param ip {@link InetAddress} to be converted to URI string literal 433 * @return {@code String} containing URI-safe string literal 434 */ 435 public static String toUriString(InetAddress ip) { 436 if (ip instanceof Inet6Address) { 437 return "[" + toAddrString(ip) + "]"; 438 } 439 return toAddrString(ip); 440 } 441 442 /** 443 * Returns an InetAddress representing the literal IPv4 or IPv6 host portion of a URL, encoded in 444 * the format specified by RFC 3986 section 3.2.2. 445 * 446 * <p>This function is similar to {@link InetAddresses#forString(String)}, however, it requires 447 * that IPv6 addresses are surrounded by square brackets. 448 * 449 * <p>This function is the inverse of {@link InetAddresses#toUriString(java.net.InetAddress)}. 450 * 451 * @param hostAddr A RFC 3986 section 3.2.2 encoded IPv4 or IPv6 address 452 * @return an InetAddress representing the address in {@code hostAddr} 453 * @throws IllegalArgumentException if {@code hostAddr} is not a valid IPv4 address, or IPv6 454 * address surrounded by square brackets 455 */ 456 public static InetAddress forUriString(String hostAddr) { 457 InetAddress addr = forUriStringNoThrow(hostAddr); 458 if (addr == null) { 459 throw formatIllegalArgumentException("Not a valid URI IP literal: '%s'", hostAddr); 460 } 461 462 return addr; 463 } 464 465 @NullableDecl 466 private static InetAddress forUriStringNoThrow(String hostAddr) { 467 checkNotNull(hostAddr); 468 469 // Decide if this should be an IPv6 or IPv4 address. 470 String ipString; 471 int expectBytes; 472 if (hostAddr.startsWith("[") && hostAddr.endsWith("]")) { 473 ipString = hostAddr.substring(1, hostAddr.length() - 1); 474 expectBytes = 16; 475 } else { 476 ipString = hostAddr; 477 expectBytes = 4; 478 } 479 480 // Parse the address, and make sure the length/version is correct. 481 byte[] addr = ipStringToBytes(ipString); 482 if (addr == null || addr.length != expectBytes) { 483 return null; 484 } 485 486 return bytesToInetAddress(addr); 487 } 488 489 /** 490 * Returns {@code true} if the supplied string is a valid URI IP string literal, {@code false} 491 * otherwise. 492 * 493 * @param ipString {@code String} to evaluated as an IP URI host string literal 494 * @return {@code true} if the argument is a valid IP URI host 495 */ 496 public static boolean isUriInetAddress(String ipString) { 497 return forUriStringNoThrow(ipString) != null; 498 } 499 500 /** 501 * Evaluates whether the argument is an IPv6 "compat" address. 502 * 503 * <p>An "IPv4 compatible", or "compat", address is one with 96 leading bits of zero, with the 504 * remaining 32 bits interpreted as an IPv4 address. These are conventionally represented in 505 * string literals as {@code "::192.168.0.1"}, though {@code "::c0a8:1"} is also considered an 506 * IPv4 compatible address (and equivalent to {@code "::192.168.0.1"}). 507 * 508 * <p>For more on IPv4 compatible addresses see section 2.5.5.1 of <a target="_parent" 509 * href="http://tools.ietf.org/html/rfc4291#section-2.5.5.1">RFC 4291</a>. 510 * 511 * <p>NOTE: This method is different from {@link Inet6Address#isIPv4CompatibleAddress} in that it 512 * more correctly classifies {@code "::"} and {@code "::1"} as proper IPv6 addresses (which they 513 * are), NOT IPv4 compatible addresses (which they are generally NOT considered to be). 514 * 515 * @param ip {@link Inet6Address} to be examined for embedded IPv4 compatible address format 516 * @return {@code true} if the argument is a valid "compat" address 517 */ 518 public static boolean isCompatIPv4Address(Inet6Address ip) { 519 if (!ip.isIPv4CompatibleAddress()) { 520 return false; 521 } 522 523 byte[] bytes = ip.getAddress(); 524 if ((bytes[12] == 0) 525 && (bytes[13] == 0) 526 && (bytes[14] == 0) 527 && ((bytes[15] == 0) || (bytes[15] == 1))) { 528 return false; 529 } 530 531 return true; 532 } 533 534 /** 535 * Returns the IPv4 address embedded in an IPv4 compatible address. 536 * 537 * @param ip {@link Inet6Address} to be examined for an embedded IPv4 address 538 * @return {@link Inet4Address} of the embedded IPv4 address 539 * @throws IllegalArgumentException if the argument is not a valid IPv4 compatible address 540 */ 541 public static Inet4Address getCompatIPv4Address(Inet6Address ip) { 542 checkArgument( 543 isCompatIPv4Address(ip), "Address '%s' is not IPv4-compatible.", toAddrString(ip)); 544 545 return getInet4Address(Arrays.copyOfRange(ip.getAddress(), 12, 16)); 546 } 547 548 /** 549 * Evaluates whether the argument is a 6to4 address. 550 * 551 * <p>6to4 addresses begin with the {@code "2002::/16"} prefix. The next 32 bits are the IPv4 552 * address of the host to which IPv6-in-IPv4 tunneled packets should be routed. 553 * 554 * <p>For more on 6to4 addresses see section 2 of <a target="_parent" 555 * href="http://tools.ietf.org/html/rfc3056#section-2">RFC 3056</a>. 556 * 557 * @param ip {@link Inet6Address} to be examined for 6to4 address format 558 * @return {@code true} if the argument is a 6to4 address 559 */ 560 public static boolean is6to4Address(Inet6Address ip) { 561 byte[] bytes = ip.getAddress(); 562 return (bytes[0] == (byte) 0x20) && (bytes[1] == (byte) 0x02); 563 } 564 565 /** 566 * Returns the IPv4 address embedded in a 6to4 address. 567 * 568 * @param ip {@link Inet6Address} to be examined for embedded IPv4 in 6to4 address 569 * @return {@link Inet4Address} of embedded IPv4 in 6to4 address 570 * @throws IllegalArgumentException if the argument is not a valid IPv6 6to4 address 571 */ 572 public static Inet4Address get6to4IPv4Address(Inet6Address ip) { 573 checkArgument(is6to4Address(ip), "Address '%s' is not a 6to4 address.", toAddrString(ip)); 574 575 return getInet4Address(Arrays.copyOfRange(ip.getAddress(), 2, 6)); 576 } 577 578 /** 579 * A simple immutable data class to encapsulate the information to be found in a Teredo address. 580 * 581 * <p>All of the fields in this class are encoded in various portions of the IPv6 address as part 582 * of the protocol. More protocols details can be found at: <a target="_parent" 583 * href="http://en.wikipedia.org/wiki/Teredo_tunneling">http://en.wikipedia. 584 * org/wiki/Teredo_tunneling</a>. 585 * 586 * <p>The RFC can be found here: <a target="_parent" href="http://tools.ietf.org/html/rfc4380">RFC 587 * 4380</a>. 588 * 589 * @since 5.0 590 */ 591 @Beta 592 public static final class TeredoInfo { 593 private final Inet4Address server; 594 private final Inet4Address client; 595 private final int port; 596 private final int flags; 597 598 /** 599 * Constructs a TeredoInfo instance. 600 * 601 * <p>Both server and client can be {@code null}, in which case the value {@code "0.0.0.0"} will 602 * be assumed. 603 * 604 * @throws IllegalArgumentException if either of the {@code port} or the {@code flags} arguments 605 * are out of range of an unsigned short 606 */ 607 // TODO: why is this public? 608 public TeredoInfo( 609 @NullableDecl Inet4Address server, @NullableDecl Inet4Address client, int port, int flags) { 610 checkArgument( 611 (port >= 0) && (port <= 0xffff), "port '%s' is out of range (0 <= port <= 0xffff)", port); 612 checkArgument( 613 (flags >= 0) && (flags <= 0xffff), 614 "flags '%s' is out of range (0 <= flags <= 0xffff)", 615 flags); 616 617 this.server = MoreObjects.firstNonNull(server, ANY4); 618 this.client = MoreObjects.firstNonNull(client, ANY4); 619 this.port = port; 620 this.flags = flags; 621 } 622 623 public Inet4Address getServer() { 624 return server; 625 } 626 627 public Inet4Address getClient() { 628 return client; 629 } 630 631 public int getPort() { 632 return port; 633 } 634 635 public int getFlags() { 636 return flags; 637 } 638 } 639 640 /** 641 * Evaluates whether the argument is a Teredo address. 642 * 643 * <p>Teredo addresses begin with the {@code "2001::/32"} prefix. 644 * 645 * @param ip {@link Inet6Address} to be examined for Teredo address format 646 * @return {@code true} if the argument is a Teredo address 647 */ 648 public static boolean isTeredoAddress(Inet6Address ip) { 649 byte[] bytes = ip.getAddress(); 650 return (bytes[0] == (byte) 0x20) 651 && (bytes[1] == (byte) 0x01) 652 && (bytes[2] == 0) 653 && (bytes[3] == 0); 654 } 655 656 /** 657 * Returns the Teredo information embedded in a Teredo address. 658 * 659 * @param ip {@link Inet6Address} to be examined for embedded Teredo information 660 * @return extracted {@code TeredoInfo} 661 * @throws IllegalArgumentException if the argument is not a valid IPv6 Teredo address 662 */ 663 public static TeredoInfo getTeredoInfo(Inet6Address ip) { 664 checkArgument(isTeredoAddress(ip), "Address '%s' is not a Teredo address.", toAddrString(ip)); 665 666 byte[] bytes = ip.getAddress(); 667 Inet4Address server = getInet4Address(Arrays.copyOfRange(bytes, 4, 8)); 668 669 int flags = ByteStreams.newDataInput(bytes, 8).readShort() & 0xffff; 670 671 // Teredo obfuscates the mapped client port, per section 4 of the RFC. 672 int port = ~ByteStreams.newDataInput(bytes, 10).readShort() & 0xffff; 673 674 byte[] clientBytes = Arrays.copyOfRange(bytes, 12, 16); 675 for (int i = 0; i < clientBytes.length; i++) { 676 // Teredo obfuscates the mapped client IP, per section 4 of the RFC. 677 clientBytes[i] = (byte) ~clientBytes[i]; 678 } 679 Inet4Address client = getInet4Address(clientBytes); 680 681 return new TeredoInfo(server, client, port, flags); 682 } 683 684 /** 685 * Evaluates whether the argument is an ISATAP address. 686 * 687 * <p>From RFC 5214: "ISATAP interface identifiers are constructed in Modified EUI-64 format [...] 688 * by concatenating the 24-bit IANA OUI (00-00-5E), the 8-bit hexadecimal value 0xFE, and a 32-bit 689 * IPv4 address in network byte order [...]" 690 * 691 * <p>For more on ISATAP addresses see section 6.1 of <a target="_parent" 692 * href="http://tools.ietf.org/html/rfc5214#section-6.1">RFC 5214</a>. 693 * 694 * @param ip {@link Inet6Address} to be examined for ISATAP address format 695 * @return {@code true} if the argument is an ISATAP address 696 */ 697 public static boolean isIsatapAddress(Inet6Address ip) { 698 699 // If it's a Teredo address with the right port (41217, or 0xa101) 700 // which would be encoded as 0x5efe then it can't be an ISATAP address. 701 if (isTeredoAddress(ip)) { 702 return false; 703 } 704 705 byte[] bytes = ip.getAddress(); 706 707 if ((bytes[8] | (byte) 0x03) != (byte) 0x03) { 708 709 // Verify that high byte of the 64 bit identifier is zero, modulo 710 // the U/L and G bits, with which we are not concerned. 711 return false; 712 } 713 714 return (bytes[9] == (byte) 0x00) && (bytes[10] == (byte) 0x5e) && (bytes[11] == (byte) 0xfe); 715 } 716 717 /** 718 * Returns the IPv4 address embedded in an ISATAP address. 719 * 720 * @param ip {@link Inet6Address} to be examined for embedded IPv4 in ISATAP address 721 * @return {@link Inet4Address} of embedded IPv4 in an ISATAP address 722 * @throws IllegalArgumentException if the argument is not a valid IPv6 ISATAP address 723 */ 724 public static Inet4Address getIsatapIPv4Address(Inet6Address ip) { 725 checkArgument(isIsatapAddress(ip), "Address '%s' is not an ISATAP address.", toAddrString(ip)); 726 727 return getInet4Address(Arrays.copyOfRange(ip.getAddress(), 12, 16)); 728 } 729 730 /** 731 * Examines the Inet6Address to determine if it is an IPv6 address of one of the specified address 732 * types that contain an embedded IPv4 address. 733 * 734 * <p>NOTE: ISATAP addresses are explicitly excluded from this method due to their trivial 735 * spoofability. With other transition addresses spoofing involves (at least) infection of one's 736 * BGP routing table. 737 * 738 * @param ip {@link Inet6Address} to be examined for embedded IPv4 client address 739 * @return {@code true} if there is an embedded IPv4 client address 740 * @since 7.0 741 */ 742 public static boolean hasEmbeddedIPv4ClientAddress(Inet6Address ip) { 743 return isCompatIPv4Address(ip) || is6to4Address(ip) || isTeredoAddress(ip); 744 } 745 746 /** 747 * Examines the Inet6Address to extract the embedded IPv4 client address if the InetAddress is an 748 * IPv6 address of one of the specified address types that contain an embedded IPv4 address. 749 * 750 * <p>NOTE: ISATAP addresses are explicitly excluded from this method due to their trivial 751 * spoofability. With other transition addresses spoofing involves (at least) infection of one's 752 * BGP routing table. 753 * 754 * @param ip {@link Inet6Address} to be examined for embedded IPv4 client address 755 * @return {@link Inet4Address} of embedded IPv4 client address 756 * @throws IllegalArgumentException if the argument does not have a valid embedded IPv4 address 757 */ 758 public static Inet4Address getEmbeddedIPv4ClientAddress(Inet6Address ip) { 759 if (isCompatIPv4Address(ip)) { 760 return getCompatIPv4Address(ip); 761 } 762 763 if (is6to4Address(ip)) { 764 return get6to4IPv4Address(ip); 765 } 766 767 if (isTeredoAddress(ip)) { 768 return getTeredoInfo(ip).getClient(); 769 } 770 771 throw formatIllegalArgumentException("'%s' has no embedded IPv4 address.", toAddrString(ip)); 772 } 773 774 /** 775 * Evaluates whether the argument is an "IPv4 mapped" IPv6 address. 776 * 777 * <p>An "IPv4 mapped" address is anything in the range ::ffff:0:0/96 (sometimes written as 778 * ::ffff:0.0.0.0/96), with the last 32 bits interpreted as an IPv4 address. 779 * 780 * <p>For more on IPv4 mapped addresses see section 2.5.5.2 of <a target="_parent" 781 * href="http://tools.ietf.org/html/rfc4291#section-2.5.5.2">RFC 4291</a>. 782 * 783 * <p>Note: This method takes a {@code String} argument because {@link InetAddress} automatically 784 * collapses mapped addresses to IPv4. (It is actually possible to avoid this using one of the 785 * obscure {@link Inet6Address} methods, but it would be unwise to depend on such a 786 * poorly-documented feature.) 787 * 788 * @param ipString {@code String} to be examined for embedded IPv4-mapped IPv6 address format 789 * @return {@code true} if the argument is a valid "mapped" address 790 * @since 10.0 791 */ 792 public static boolean isMappedIPv4Address(String ipString) { 793 byte[] bytes = ipStringToBytes(ipString); 794 if (bytes != null && bytes.length == 16) { 795 for (int i = 0; i < 10; i++) { 796 if (bytes[i] != 0) { 797 return false; 798 } 799 } 800 for (int i = 10; i < 12; i++) { 801 if (bytes[i] != (byte) 0xff) { 802 return false; 803 } 804 } 805 return true; 806 } 807 return false; 808 } 809 810 /** 811 * Coerces an IPv6 address into an IPv4 address. 812 * 813 * <p>HACK: As long as applications continue to use IPv4 addresses for indexing into tables, 814 * accounting, et cetera, it may be necessary to <b>coerce</b> IPv6 addresses into IPv4 addresses. 815 * This function does so by hashing the upper 64 bits into {@code 224.0.0.0/3} (64 bits into 29 816 * bits). 817 * 818 * <p>A "coerced" IPv4 address is equivalent to itself. 819 * 820 * <p>NOTE: This function is failsafe for security purposes: ALL IPv6 addresses (except localhost 821 * (::1)) are hashed to avoid the security risk associated with extracting an embedded IPv4 822 * address that might permit elevated privileges. 823 * 824 * @param ip {@link InetAddress} to "coerce" 825 * @return {@link Inet4Address} represented "coerced" address 826 * @since 7.0 827 */ 828 public static Inet4Address getCoercedIPv4Address(InetAddress ip) { 829 if (ip instanceof Inet4Address) { 830 return (Inet4Address) ip; 831 } 832 833 // Special cases: 834 byte[] bytes = ip.getAddress(); 835 boolean leadingBytesOfZero = true; 836 for (int i = 0; i < 15; ++i) { 837 if (bytes[i] != 0) { 838 leadingBytesOfZero = false; 839 break; 840 } 841 } 842 if (leadingBytesOfZero && (bytes[15] == 1)) { 843 return LOOPBACK4; // ::1 844 } else if (leadingBytesOfZero && (bytes[15] == 0)) { 845 return ANY4; // ::0 846 } 847 848 Inet6Address ip6 = (Inet6Address) ip; 849 long addressAsLong = 0; 850 if (hasEmbeddedIPv4ClientAddress(ip6)) { 851 addressAsLong = getEmbeddedIPv4ClientAddress(ip6).hashCode(); 852 } else { 853 854 // Just extract the high 64 bits (assuming the rest is user-modifiable). 855 addressAsLong = ByteBuffer.wrap(ip6.getAddress(), 0, 8).getLong(); 856 } 857 858 // Many strategies for hashing are possible. This might suffice for now. 859 int coercedHash = Hashing.murmur3_32().hashLong(addressAsLong).asInt(); 860 861 // Squash into 224/4 Multicast and 240/4 Reserved space (i.e. 224/3). 862 coercedHash |= 0xe0000000; 863 864 // Fixup to avoid some "illegal" values. Currently the only potential 865 // illegal value is 255.255.255.255. 866 if (coercedHash == 0xffffffff) { 867 coercedHash = 0xfffffffe; 868 } 869 870 return getInet4Address(Ints.toByteArray(coercedHash)); 871 } 872 873 /** 874 * Returns an integer representing an IPv4 address regardless of whether the supplied argument is 875 * an IPv4 address or not. 876 * 877 * <p>IPv6 addresses are <b>coerced</b> to IPv4 addresses before being converted to integers. 878 * 879 * <p>As long as there are applications that assume that all IP addresses are IPv4 addresses and 880 * can therefore be converted safely to integers (for whatever purpose) this function can be used 881 * to handle IPv6 addresses as well until the application is suitably fixed. 882 * 883 * <p>NOTE: an IPv6 address coerced to an IPv4 address can only be used for such purposes as 884 * rudimentary identification or indexing into a collection of real {@link InetAddress}es. They 885 * cannot be used as real addresses for the purposes of network communication. 886 * 887 * @param ip {@link InetAddress} to convert 888 * @return {@code int}, "coerced" if ip is not an IPv4 address 889 * @since 7.0 890 */ 891 public static int coerceToInteger(InetAddress ip) { 892 return ByteStreams.newDataInput(getCoercedIPv4Address(ip).getAddress()).readInt(); 893 } 894 895 /** 896 * Returns an Inet4Address having the integer value specified by the argument. 897 * 898 * @param address {@code int}, the 32bit integer address to be converted 899 * @return {@link Inet4Address} equivalent of the argument 900 */ 901 public static Inet4Address fromInteger(int address) { 902 return getInet4Address(Ints.toByteArray(address)); 903 } 904 905 /** 906 * Returns an address from a <b>little-endian ordered</b> byte array (the opposite of what {@link 907 * InetAddress#getByAddress} expects). 908 * 909 * <p>IPv4 address byte array must be 4 bytes long and IPv6 byte array must be 16 bytes long. 910 * 911 * @param addr the raw IP address in little-endian byte order 912 * @return an InetAddress object created from the raw IP address 913 * @throws UnknownHostException if IP address is of illegal length 914 */ 915 public static InetAddress fromLittleEndianByteArray(byte[] addr) throws UnknownHostException { 916 byte[] reversed = new byte[addr.length]; 917 for (int i = 0; i < addr.length; i++) { 918 reversed[i] = addr[addr.length - i - 1]; 919 } 920 return InetAddress.getByAddress(reversed); 921 } 922 923 /** 924 * Returns a new InetAddress that is one less than the passed in address. This method works for 925 * both IPv4 and IPv6 addresses. 926 * 927 * @param address the InetAddress to decrement 928 * @return a new InetAddress that is one less than the passed in address 929 * @throws IllegalArgumentException if InetAddress is at the beginning of its range 930 * @since 18.0 931 */ 932 public static InetAddress decrement(InetAddress address) { 933 byte[] addr = address.getAddress(); 934 int i = addr.length - 1; 935 while (i >= 0 && addr[i] == (byte) 0x00) { 936 addr[i] = (byte) 0xff; 937 i--; 938 } 939 940 checkArgument(i >= 0, "Decrementing %s would wrap.", address); 941 942 addr[i]--; 943 return bytesToInetAddress(addr); 944 } 945 946 /** 947 * Returns a new InetAddress that is one more than the passed in address. This method works for 948 * both IPv4 and IPv6 addresses. 949 * 950 * @param address the InetAddress to increment 951 * @return a new InetAddress that is one more than the passed in address 952 * @throws IllegalArgumentException if InetAddress is at the end of its range 953 * @since 10.0 954 */ 955 public static InetAddress increment(InetAddress address) { 956 byte[] addr = address.getAddress(); 957 int i = addr.length - 1; 958 while (i >= 0 && addr[i] == (byte) 0xff) { 959 addr[i] = 0; 960 i--; 961 } 962 963 checkArgument(i >= 0, "Incrementing %s would wrap.", address); 964 965 addr[i]++; 966 return bytesToInetAddress(addr); 967 } 968 969 /** 970 * Returns true if the InetAddress is either 255.255.255.255 for IPv4 or 971 * ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff for IPv6. 972 * 973 * @return true if the InetAddress is either 255.255.255.255 for IPv4 or 974 * ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff for IPv6 975 * @since 10.0 976 */ 977 public static boolean isMaximum(InetAddress address) { 978 byte[] addr = address.getAddress(); 979 for (int i = 0; i < addr.length; i++) { 980 if (addr[i] != (byte) 0xff) { 981 return false; 982 } 983 } 984 return true; 985 } 986 987 private static IllegalArgumentException formatIllegalArgumentException( 988 String format, Object... args) { 989 return new IllegalArgumentException(String.format(Locale.ROOT, format, args)); 990 } 991}