001 /*
002 * Copyright (C) 2008 Google Inc.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017 package com.google.common.net;
018
019 import com.google.common.annotations.Beta;
020 import com.google.common.base.Preconditions;
021 import com.google.common.io.ByteStreams;
022 import com.google.common.primitives.Ints;
023
024 import java.net.Inet4Address;
025 import java.net.Inet6Address;
026 import java.net.InetAddress;
027 import java.net.UnknownHostException;
028 import java.util.Arrays;
029 import java.util.Locale;
030
031 import javax.annotation.Nullable;
032
033 /**
034 * Static utility methods pertaining to {@link InetAddress} instances.
035 *
036 * <p><b>Important note:</b> Unlike {@code InetAddress.getByName()}, the
037 * methods of this class never cause DNS services to be accessed. For
038 * this reason, you should prefer these methods as much as possible over
039 * their JDK equivalents whenever you are expecting to handle only
040 * IP address string literals -- there is no blocking DNS penalty for a
041 * malformed string.
042 *
043 * <p>This class hooks into the {@code sun.net.util.IPAddressUtil} class
044 * to make use of the {@code textToNumericFormatV4} and
045 * {@code textToNumericFormatV6} methods directly as a means to avoid
046 * accidentally traversing all nameservices (it can be vitally important
047 * to avoid, say, blocking on DNS at times).
048 *
049 * <p>When dealing with {@link Inet4Address} and {@link Inet6Address}
050 * objects as byte arrays (vis. {@code InetAddress.getAddress()}) they
051 * are 4 and 16 bytes in length, respectively, and represent the address
052 * in network byte order.
053 *
054 * <p>Examples of IP addresses and their byte representations:
055 * <ul>
056 * <li>The IPv4 loopback address, {@code "127.0.0.1"}.<br/>
057 * {@code 7f 00 00 01}
058 *
059 * <li>The IPv6 loopback address, {@code "::1"}.<br/>
060 * {@code 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01}
061 *
062 * <li>From the IPv6 reserved documentation prefix ({@code 2001:db8::/32}),
063 * {@code "2001:db8::1"}.<br/>
064 * {@code 20 01 0d b8 00 00 00 00 00 00 00 00 00 00 00 01}
065 *
066 * <li>An IPv6 "IPv4 compatible" (or "compat") address,
067 * {@code "::192.168.0.1"}.<br/>
068 * {@code 00 00 00 00 00 00 00 00 00 00 00 00 c0 a8 00 01}
069 *
070 * <li>An IPv6 "IPv4 mapped" address, {@code "::ffff:192.168.0.1"}.<br/>
071 * {@code 00 00 00 00 00 00 00 00 00 00 ff ff c0 a8 00 01}
072 * </ul>
073 *
074 * <p>A few notes about IPv6 "IPv4 mapped" addresses and their observed
075 * use in Java.
076 * <br><br>
077 * "IPv4 mapped" addresses were originally a representation of IPv4
078 * addresses for use on an IPv6 socket that could receive both IPv4
079 * and IPv6 connections (by disabling the {@code IPV6_V6ONLY} socket
080 * option on an IPv6 socket). Yes, it's confusing. Nevertheless,
081 * these "mapped" addresses were never supposed to be seen on the
082 * wire. That assumption was dropped, some say mistakenly, in later
083 * RFCs with the apparent aim of making IPv4-to-IPv6 transition simpler.
084 *
085 * <p>Technically one <i>can</i> create a 128bit IPv6 address with the wire
086 * format of a "mapped" address, as shown above, and transmit it in an
087 * IPv6 packet header. However, Java's InetAddress creation methods
088 * appear to adhere doggedly to the original intent of the "mapped"
089 * address: all "mapped" addresses return {@link Inet4Address} objects.
090 *
091 * <p>For added safety, it is common for IPv6 network operators to filter
092 * all packets where either the source or destination address appears to
093 * be a "compat" or "mapped" address. Filtering suggestions usually
094 * recommend discarding any packets with source or destination addresses
095 * in the invalid range {@code ::/3}, which includes both of these bizarre
096 * address formats. For more information on "bogons", including lists
097 * of IPv6 bogon space, see:
098 *
099 * <ul>
100 * <li><a target="_parent"
101 * href="http://en.wikipedia.org/wiki/Bogon_filtering"
102 * >http://en.wikipedia.org/wiki/Bogon_filtering</a>
103 * <li><a target="_parent"
104 * href="http://www.cymru.com/Bogons/ipv6.txt"
105 * >http://www.cymru.com/Bogons/ipv6.txt</a>
106 * <li><a target="_parent"
107 * href="http://www.cymru.com/Bogons/v6bogon.html"
108 * >http://www.cymru.com/Bogons/v6bogon.html</a>
109 * <li><a target="_parent"
110 * href="http://www.space.net/~gert/RIPE/ipv6-filters.html"
111 * >http://www.space.net/~gert/RIPE/ipv6-filters.html</a>
112 * </ul>
113 *
114 * @author Erik Kline
115 * @since 5
116 */
117 @Beta
118 public final class InetAddresses {
119
120 private static final int IPV4_PART_COUNT = 4;
121 private static final int IPV6_PART_COUNT = 8;
122 private static final Inet4Address LOOPBACK4 =
123 (Inet4Address) forString("127.0.0.1");
124 private static final Inet4Address ANY4 =
125 (Inet4Address) forString("0.0.0.0");
126
127 private InetAddresses() {}
128
129 /**
130 * Returns an {@link Inet4Address}, given a byte array representation
131 * of the IPv4 address.
132 *
133 * @param bytes byte array representing an IPv4 address (should be
134 * of length 4).
135 * @return {@link Inet4Address} corresponding to the supplied byte
136 * array.
137 * @throws IllegalArgumentException if a valid {@link Inet4Address}
138 * can not be created.
139 */
140 private static Inet4Address getInet4Address(byte[] bytes) {
141 Preconditions.checkArgument(bytes.length == 4,
142 "Byte array has invalid length for an IPv4 address: %s != 4.",
143 bytes.length);
144
145 try {
146 InetAddress ipv4 = InetAddress.getByAddress(bytes);
147 if (!(ipv4 instanceof Inet4Address)) {
148 throw new UnknownHostException(
149 String.format("'%s' is not an IPv4 address.",
150 ipv4.getHostAddress()));
151 }
152
153 return (Inet4Address) ipv4;
154 } catch (UnknownHostException e) {
155
156 /*
157 * This really shouldn't happen in practice since all our byte
158 * sequences should be valid IP addresses.
159 *
160 * However {@link InetAddress#getByAddress} is documented as
161 * potentially throwing this "if IP address is of illegal length".
162 *
163 * This is mapped to IllegalArgumentException since, presumably,
164 * the argument triggered some bizarre processing bug.
165 */
166 throw new IllegalArgumentException(
167 String.format("Host address '%s' is not a valid IPv4 address.",
168 Arrays.toString(bytes)),
169 e);
170 }
171 }
172
173 /**
174 * Returns the {@link InetAddress} having the given string
175 * representation.
176 *
177 * <p>This deliberately avoids all nameservice lookups (e.g. no DNS).
178 *
179 * @param ipString {@code String} containing an IPv4 or IPv6 string literal,
180 * e.g. {@code "192.168.0.1"} or {@code "2001:db8::1"}
181 * @return {@link InetAddress} representing the argument
182 * @throws IllegalArgumentException if the argument is not a valid
183 * IP string literal
184 */
185 public static InetAddress forString(String ipString) {
186 byte[] addr = textToNumericFormatV4(ipString);
187 if (addr == null) {
188 // Scanning for IPv4 string literal failed; try IPv6.
189 addr = textToNumericFormatV6(ipString);
190 }
191
192 // The argument was malformed, i.e. not an IP string literal.
193 if (addr == null) {
194 throw new IllegalArgumentException(
195 String.format("'%s' is not an IP string literal.", ipString));
196 }
197
198 try {
199 return InetAddress.getByAddress(addr);
200 } catch (UnknownHostException e) {
201
202 /*
203 * This really shouldn't happen in practice since all our byte
204 * sequences should be valid IP addresses.
205 *
206 * However {@link InetAddress#getByAddress} is documented as
207 * potentially throwing this "if IP address is of illegal length".
208 *
209 * This is mapped to IllegalArgumentException since, presumably,
210 * the argument triggered some processing bug in either
211 * {@link IPAddressUtil#textToNumericFormatV4} or
212 * {@link IPAddressUtil#textToNumericFormatV6}.
213 */
214 throw new IllegalArgumentException(
215 String.format("'%s' is extremely broken.", ipString), e);
216 }
217 }
218
219 /**
220 * Returns {@code true} if the supplied string is a valid IP string
221 * literal, {@code false} otherwise.
222 *
223 * @param ipString {@code String} to evaluated as an IP string literal
224 * @return {@code true} if the argument is a valid IP string literal
225 */
226 public static boolean isInetAddress(String ipString) {
227 try {
228 forString(ipString);
229 return true;
230 } catch (IllegalArgumentException e) {
231 return false;
232 }
233 }
234
235 private static byte[] textToNumericFormatV4(String ipString) {
236
237 boolean isIpv6 = false;
238
239 // handle IPv6 forms of IPv4 addresses
240 // TODO: use Ascii.toUpperCase() when available
241 if (ipString.toUpperCase(Locale.US).startsWith("::FFFF:")) {
242 ipString = ipString.substring(7);
243 } else if (ipString.startsWith("::")) {
244 ipString = ipString.substring(2);
245 isIpv6 = true;
246 }
247
248 String[] address = ipString.split("\\.");
249 if (address.length != IPV4_PART_COUNT) {
250 return null;
251 }
252 try {
253 byte[] bytes = new byte[IPV4_PART_COUNT];
254 for (int i = 0; i < bytes.length; i++) {
255 int piece = Integer.parseInt(address[i]);
256 if (piece < 0 || piece > 255) {
257 return null;
258 }
259
260 // No leading zeroes are allowed. See
261 // http://tools.ietf.org/html/draft-main-ipaddr-text-rep-00
262 // section 2.1 for discussion.
263
264 if (address[i].startsWith("0") && address[i].length() != 1) {
265 return null;
266 }
267 bytes[i] = (byte) piece;
268 }
269
270 if (isIpv6) { // prepend with zeroes;
271 byte[] data = new byte[2 * IPV6_PART_COUNT]; // Java initializes arrays to zero
272 System.arraycopy(bytes, 0, data, 12, IPV4_PART_COUNT);
273 return data;
274 } else {
275 return bytes;
276 }
277 } catch (NumberFormatException ex) {
278 return null;
279 }
280 }
281
282 private static byte[] textToNumericFormatV6(String ipString) {
283 if (!ipString.contains(":")) {
284 return null;
285 }
286 if (ipString.contains(":::")) {
287 return null;
288 }
289
290 if (ipString.contains(".")) {
291 ipString = convertDottedQuadToHex(ipString);
292 if (ipString == null) {
293 return null;
294 }
295 }
296
297 ipString = padIpString(ipString);
298 try {
299 String[] address = ipString.split(":", IPV6_PART_COUNT);
300 if (address.length != IPV6_PART_COUNT) {
301 return null;
302 }
303 byte[] bytes = new byte[2 * IPV6_PART_COUNT];
304 for (int i = 0; i < IPV6_PART_COUNT; i++) {
305 int piece = address[i].equals("") ? 0 : Integer.parseInt(address[i], 16);
306 bytes[2 * i] = (byte) ((piece & 0xFF00) >>> 8);
307 bytes[2 * i + 1] = (byte) (piece & 0xFF);
308 }
309 return bytes;
310 } catch (NumberFormatException ex) {
311 return null;
312 }
313 }
314
315 // Fill in any omitted colons
316 private static String padIpString(String ipString) {
317 if (ipString.contains("::")) {
318 int count = numberOfColons(ipString);
319 StringBuilder buffer = new StringBuilder("::");
320 for (int i = 0; i + count < 7; i++) {
321 buffer.append(":");
322 }
323 ipString = ipString.replace("::", buffer);
324 }
325 return ipString;
326 }
327
328 private static int numberOfColons(String s) {
329 int count = 0;
330 for (int i = 0; i < s.length(); i++) {
331 if (s.charAt(i) == ':') {
332 count++;
333 }
334 }
335 return count;
336 }
337
338 private static String convertDottedQuadToHex(String ipString) {
339 int lastColon = ipString.lastIndexOf(':');
340 String initialPart = ipString.substring(0, lastColon + 1);
341 String dottedQuad = ipString.substring(lastColon + 1);
342 byte[] quad = textToNumericFormatV4(dottedQuad);
343 if (quad == null) {
344 return null;
345 }
346 String penultimate = Integer.toHexString(((quad[0] & 0xff) << 8) | (quad[1] & 0xff));
347 String ultimate = Integer.toHexString(((quad[2] & 0xff) << 8) | (quad[3] & 0xff));
348 return initialPart + penultimate + ":" + ultimate;
349 }
350
351 /**
352 * Returns the string representation of an {@link InetAddress} suitable
353 * for inclusion in a URI.
354 *
355 * <p>For IPv4 addresses, this is identical to
356 * {@link InetAddress#getHostAddress()}, but for IPv6 addresses it
357 * surrounds this text with square brackets; for example
358 * {@code "[2001:db8::1]"}.
359 *
360 * <p>Per section 3.2.2 of
361 * <a target="_parent"
362 * href="http://tools.ietf.org/html/rfc3986#section-3.2.2"
363 * >http://tools.ietf.org/html/rfc3986</a>,
364 * a URI containing an IPv6 string literal is of the form
365 * {@code "http://[2001:db8::1]:8888/index.html"}.
366 *
367 * <p>Use of either {@link InetAddress#getHostAddress()} or this
368 * method is recommended over {@link InetAddress#toString()} when an
369 * IP address string literal is desired. This is because
370 * {@link InetAddress#toString()} prints the hostname and the IP
371 * address string joined by a "/".
372 *
373 * @param ip {@link InetAddress} to be converted to URI string literal
374 * @return {@code String} containing URI-safe string literal
375 */
376 public static String toUriString(InetAddress ip) {
377 if (ip instanceof Inet6Address) {
378 return "[" + ip.getHostAddress() + "]";
379 }
380 return ip.getHostAddress();
381 }
382
383 /**
384 * Returns an InetAddress representing the literal IPv4 or IPv6 host
385 * portion of a URL, encoded in the format specified by RFC 3986 section 3.2.2.
386 *
387 * <p>This function is similar to {@link InetAddresses#forString(String)},
388 * however, it requires that IPv6 addresses are surrounded by square brackets.
389 *
390 * <p>This function is the inverse of
391 * {@link InetAddresses#toUriString(java.net.InetAddress)}.
392 *
393 * @param hostAddr A RFC 3986 section 3.2.2 encoded IPv4 or IPv6 address
394 * @return an InetAddress representing the address in {@code hostAddr}
395 * @throws IllegalArgumentException if {@code hostAddr} is not a valid
396 * IPv4 address, or IPv6 address surrounded by square brackets
397 */
398 public static InetAddress forUriString(String hostAddr) {
399 Preconditions.checkNotNull(hostAddr);
400 Preconditions.checkArgument(hostAddr.length() > 0, "host string is empty");
401 InetAddress retval = null;
402
403 // IPv4 address?
404 try {
405 retval = forString(hostAddr);
406 if (retval instanceof Inet4Address) {
407 return retval;
408 }
409 } catch (IllegalArgumentException e) {
410 // Not a valid IP address, fall through.
411 }
412
413 // IPv6 address
414 if (!(hostAddr.startsWith("[") && hostAddr.endsWith("]"))) {
415 throw new IllegalArgumentException("Not a valid address: \"" + hostAddr + '"');
416 }
417
418 retval = forString(hostAddr.substring(1, hostAddr.length() - 1));
419 if (retval instanceof Inet6Address) {
420 return retval;
421 }
422
423 throw new IllegalArgumentException("Not a valid address: \"" + hostAddr + '"');
424 }
425
426 /**
427 * Returns {@code true} if the supplied string is a valid URI IP string
428 * literal, {@code false} otherwise.
429 *
430 * @param ipString {@code String} to evaluated as an IP URI host string literal
431 * @return {@code true} if the argument is a valid IP URI host
432 */
433 public static boolean isUriInetAddress(String ipString) {
434 try {
435 forUriString(ipString);
436 return true;
437 } catch (IllegalArgumentException e) {
438 return false;
439 }
440 }
441
442 /**
443 * Evaluates whether the argument is an IPv6 "compat" address.
444 *
445 * <p>An "IPv4 compatible", or "compat", address is one with 96 leading
446 * bits of zero, with the remaining 32 bits interpreted as an
447 * IPv4 address. These are conventionally represented in string
448 * literals as {@code "::192.168.0.1"}, though {@code "::c0a8:1"} is
449 * also considered an IPv4 compatible address (and equivalent to
450 * {@code "::192.168.0.1"}).
451 *
452 * <p>For more on IPv4 compatible addresses see section 2.5.5.1 of
453 * <a target="_parent"
454 * href="http://tools.ietf.org/html/rfc4291#section-2.5.5.1"
455 * >http://tools.ietf.org/html/rfc4291</a>
456 *
457 * <p>NOTE: This method is different from
458 * {@link Inet6Address#isIPv4CompatibleAddress} in that it more
459 * correctly classifies {@code "::"} and {@code "::1"} as
460 * proper IPv6 addresses (which they are), NOT IPv4 compatible
461 * addresses (which they are generally NOT considered to be).
462 *
463 * @param ip {@link Inet6Address} to be examined for embedded IPv4
464 * compatible address format
465 * @return {@code true} if the argument is a valid "compat" address
466 */
467 public static boolean isCompatIPv4Address(Inet6Address ip) {
468 if (!ip.isIPv4CompatibleAddress()) {
469 return false;
470 }
471
472 byte[] bytes = ip.getAddress();
473 if ((bytes[12] == 0) && (bytes[13] == 0) && (bytes[14] == 0)
474 && ((bytes[15] == 0) || (bytes[15] == 1))) {
475 return false;
476 }
477
478 return true;
479 }
480
481 /**
482 * Returns the IPv4 address embedded in an IPv4 compatible address.
483 *
484 * @param ip {@link Inet6Address} to be examined for an embedded
485 * IPv4 address
486 * @return {@link Inet4Address} of the embedded IPv4 address
487 * @throws IllegalArgumentException if the argument is not a valid
488 * IPv4 compatible address
489 */
490 public static Inet4Address getCompatIPv4Address(Inet6Address ip) {
491 Preconditions.checkArgument(isCompatIPv4Address(ip),
492 "Address '%s' is not IPv4-compatible.", ip.getHostAddress());
493
494 return getInet4Address(copyOfRange(ip.getAddress(), 12, 16));
495 }
496
497 /**
498 * Evaluates whether the argument is a 6to4 address.
499 *
500 * <p>6to4 addresses begin with the {@code "2002::/16"} prefix.
501 * The next 32 bits are the IPv4 address of the host to which
502 * IPv6-in-IPv4 tunneled packets should be routed.
503 *
504 * <p>For more on 6to4 addresses see section 2 of
505 * <a target="_parent" href="http://tools.ietf.org/html/rfc3056#section-2"
506 * >http://tools.ietf.org/html/rfc3056</a>
507 *
508 * @param ip {@link Inet6Address} to be examined for 6to4 address
509 * format
510 * @return {@code true} if the argument is a 6to4 address
511 */
512 public static boolean is6to4Address(Inet6Address ip) {
513 byte[] bytes = ip.getAddress();
514 return (bytes[0] == (byte) 0x20) && (bytes[1] == (byte) 0x02);
515 }
516
517 /**
518 * Returns the IPv4 address embedded in a 6to4 address.
519 *
520 * @param ip {@link Inet6Address} to be examined for embedded IPv4
521 * in 6to4 address.
522 * @return {@link Inet4Address} of embedded IPv4 in 6to4 address.
523 * @throws IllegalArgumentException if the argument is not a valid
524 * IPv6 6to4 address.
525 */
526 public static Inet4Address get6to4IPv4Address(Inet6Address ip) {
527 Preconditions.checkArgument(is6to4Address(ip),
528 "Address '%s' is not a 6to4 address.", ip.getHostAddress());
529
530 return getInet4Address(copyOfRange(ip.getAddress(), 2, 6));
531 }
532
533 /**
534 * A simple data class to encapsulate the information to be found in a
535 * Teredo address.
536 *
537 * <p>All of the fields in this class are encoded in various portions
538 * of the IPv6 address as part of the protocol. More protocols details
539 * can be found at:
540 * <a target="_parent" href="http://en.wikipedia.org/wiki/Teredo_tunneling"
541 * >http://en.wikipedia.org/wiki/Teredo_tunneling</a>.
542 *
543 * <p>The RFC can be found here:
544 * <a target="_parent" href="http://tools.ietf.org/html/rfc4380"
545 * >http://tools.ietf.org/html/rfc4380</a>.
546 *
547 * @since 5
548 */
549 public static class TeredoInfo {
550 private final Inet4Address server;
551 private final Inet4Address client;
552 private final int port;
553 private final int flags;
554
555 /**
556 * Constructs a TeredoInfo instance.
557 *
558 * <p>Both server and client can be {@code null}, in which case the
559 * value {@code "0.0.0.0"} will be assumed.
560 *
561 * @throws IllegalArgumentException if either of the {@code port}
562 * or the {@code flags} arguments are out of range of an
563 * unsigned short
564 */
565 public TeredoInfo(@Nullable Inet4Address server,
566 @Nullable Inet4Address client,
567 int port, int flags) {
568 Preconditions.checkArgument((port >= 0) && (port <= 0xffff),
569 "port '%d' is out of range (0 <= port <= 0xffff)", port);
570 Preconditions.checkArgument((flags >= 0) && (flags <= 0xffff),
571 "flags '%d' is out of range (0 <= flags <= 0xffff)", flags);
572
573 if (server != null) {
574 this.server = server;
575 } else {
576 this.server = ANY4;
577 }
578
579 if (client != null) {
580 this.client = client;
581 } else {
582 this.client = ANY4;
583 }
584
585 this.port = port;
586 this.flags = flags;
587 }
588
589 public Inet4Address getServer() {
590 return server;
591 }
592
593 public Inet4Address getClient() {
594 return client;
595 }
596
597 public int getPort() {
598 return port;
599 }
600
601 public int getFlags() {
602 return flags;
603 }
604 }
605
606 /**
607 * Evaluates whether the argument is a Teredo address.
608 *
609 * <p>Teredo addresses begin with the {@code "2001::/32"} prefix.
610 *
611 * @param ip {@link Inet6Address} to be examined for Teredo address
612 * format.
613 * @return {@code true} if the argument is a Teredo address
614 */
615 public static boolean isTeredoAddress(Inet6Address ip) {
616 byte[] bytes = ip.getAddress();
617 return (bytes[0] == (byte) 0x20) && (bytes[1] == (byte) 0x01)
618 && (bytes[2] == 0) && (bytes[3] == 0);
619 }
620
621 /**
622 * Returns the Teredo information embedded in a Teredo address.
623 *
624 * @param ip {@link Inet6Address} to be examined for embedded Teredo
625 * information
626 * @return extracted {@code TeredoInfo}
627 * @throws IllegalArgumentException if the argument is not a valid
628 * IPv6 Teredo address
629 */
630 public static TeredoInfo getTeredoInfo(Inet6Address ip) {
631 Preconditions.checkArgument(isTeredoAddress(ip),
632 "Address '%s' is not a Teredo address.", ip.getHostAddress());
633
634 byte[] bytes = ip.getAddress();
635 Inet4Address server = getInet4Address(copyOfRange(bytes, 4, 8));
636
637 int flags = ByteStreams.newDataInput(bytes, 8).readShort() & 0xffff;
638
639 // Teredo obfuscates the mapped client port, per section 4 of the RFC.
640 int port = ~ByteStreams.newDataInput(bytes, 10).readShort() & 0xffff;
641
642 byte[] clientBytes = copyOfRange(bytes, 12, 16);
643 for (int i = 0; i < clientBytes.length; i++) {
644 // Teredo obfuscates the mapped client IP, per section 4 of the RFC.
645 clientBytes[i] = (byte) ~clientBytes[i];
646 }
647 Inet4Address client = getInet4Address(clientBytes);
648
649 return new TeredoInfo(server, client, port, flags);
650 }
651
652 /**
653 * Evaluates whether the argument is an ISATAP address.
654 *
655 * <p>From RFC 5214: "ISATAP interface identifiers are constructed in
656 * Modified EUI-64 format [...] by concatenating the 24-bit IANA OUI
657 * (00-00-5E), the 8-bit hexadecimal value 0xFE, and a 32-bit IPv4
658 * address in network byte order [...]"
659 *
660 * <p>For more on ISATAP addresses see section 6.1 of
661 * <a target="_parent" href="http://tools.ietf.org/html/rfc5214#section-6.1"
662 * >http://tools.ietf.org/html/rfc5214</a>
663 *
664 * @param ip {@link Inet6Address} to be examined for ISATAP address
665 * format.
666 * @return {@code true} if the argument is an ISATAP address
667 */
668 public static boolean isIsatapAddress(Inet6Address ip) {
669
670 // If it's a Teredo address with the right port (41217, or 0xa101)
671 // which would be encoded as 0x5efe then it can't be an ISATAP address.
672 if (isTeredoAddress(ip)) {
673 return false;
674 }
675
676 byte[] bytes = ip.getAddress();
677
678 if ((bytes[8] | (byte) 0x03) != (byte) 0x03) {
679
680 // Verify that high byte of the 64 bit identifier is zero, modulo
681 // the U/L and G bits, with which we are not concerned.
682 return false;
683 }
684
685 return (bytes[9] == (byte) 0x00) && (bytes[10] == (byte) 0x5e)
686 && (bytes[11] == (byte) 0xfe);
687 }
688
689 /**
690 * Returns the IPv4 address embedded in an ISATAP address.
691 *
692 * @param ip {@link Inet6Address} to be examined for embedded IPv4
693 * in ISATAP address
694 * @return {@link Inet4Address} of embedded IPv4 in an ISATAP address
695 * @throws IllegalArgumentException if the argument is not a valid
696 * IPv6 ISATAP address
697 */
698 public static Inet4Address getIsatapIPv4Address(Inet6Address ip) {
699 Preconditions.checkArgument(isIsatapAddress(ip),
700 "Address '%s' is not an ISATAP address.", ip.getHostAddress());
701
702 return getInet4Address(copyOfRange(ip.getAddress(), 12, 16));
703 }
704
705 /**
706 * Examines the InetAddress to extract the embedded IPv4 client address
707 * if the InetAddress is an IPv6 address of one of the specified address
708 * types that contain an embedded IPv4 address.
709 *
710 * <p>NOTE: ISATAP addresses are explicitly excluded from this method
711 * due to their trivial spoofability. With other transition addresses
712 * spoofing involves (at least) infection of Google's BGP routing table.
713 *
714 * @param ip {@link Inet6Address} to be examined for embedded IPv4
715 * client address.
716 * @return {@link Inet4Address} of embedded IPv4 client address.
717 * @throws IllegalArgumentException if the argument does not have a valid
718 * embedded IPv4 address.
719 */
720 public static Inet4Address getEmbeddedIPv4ClientAddress(Inet6Address ip) {
721 if (isCompatIPv4Address(ip)) {
722 return getCompatIPv4Address(ip);
723 }
724
725 if (is6to4Address(ip)) {
726 return get6to4IPv4Address(ip);
727 }
728
729 if (isTeredoAddress(ip)) {
730 return getTeredoInfo(ip).getClient();
731 }
732
733 throw new IllegalArgumentException(
734 String.format("'%s' has no embedded IPv4 address.",
735 ip.getHostAddress()));
736 }
737
738 /**
739 * Returns an Inet4Address having the integer value specified by
740 * the argument.
741 *
742 * @param address {@code int}, the 32bit integer address to be converted
743 * @return {@link Inet4Address} equivalent of the argument
744 */
745 public static Inet4Address fromInteger(int address) {
746 return getInet4Address(Ints.toByteArray(address));
747 }
748
749 /**
750 * Returns an address from a <b>little-endian ordered</b> byte array
751 * (the opposite of what {@link InetAddress#getByAddress} expects).
752 *
753 * <p>IPv4 address byte array must be 4 bytes long and IPv6 byte array
754 * must be 16 bytes long.
755 *
756 * @param addr the raw IP address in little-endian byte order
757 * @return an InetAddress object created from the raw IP address
758 * @throws UnknownHostException if IP address is of illegal length
759 */
760 public static InetAddress fromLittleEndianByteArray(byte[] addr)
761 throws UnknownHostException {
762 byte[] reversed = new byte[addr.length];
763 for (int i = 0; i < addr.length; i++) {
764 reversed[i] = addr[addr.length - i - 1];
765 }
766 return InetAddress.getByAddress(reversed);
767 }
768
769 /**
770 * This method emulates the Java 6 method
771 * {@code Arrays.copyOfRange(byte, int, int)}, which is not available in
772 * Java 5, and thus cannot be used in Guava code.
773 */
774 private static byte[] copyOfRange(byte[] original, int from, int to) {
775 Preconditions.checkNotNull(original);
776
777 int end = Math.min(to, original.length);
778 byte[] result = new byte[to - from];
779
780 System.arraycopy(original, from, result, 0, end - from);
781 return result;
782 }
783 }