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