blob: 10850b070de16297234c66c46b4f00a79e08ee15 [file] [log] [blame]
Thomas Vachuska24c849c2014-10-27 09:53:05 -07001/*
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07002 * Copyright 2014 Open Networking Laboratory
Thomas Vachuska24c849c2014-10-27 09:53:05 -07003 *
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07004 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
Thomas Vachuska24c849c2014-10-27 09:53:05 -07007 *
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07008 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
Thomas Vachuska24c849c2014-10-27 09:53:05 -070015 */
Jonathan Hartdec62d42014-09-22 15:59:04 -070016package org.onlab.packet;
17
Pavlin Radoslavovd0e32d72014-10-31 18:11:43 -070018import java.net.InetAddress;
19import java.net.Inet4Address;
20import java.net.Inet6Address;
21import java.net.UnknownHostException;
Pavlin Radoslavov52307e62014-10-29 15:07:37 -070022import java.nio.ByteBuffer;
Jonathan Hartdec62d42014-09-22 15:59:04 -070023import java.util.Arrays;
Pavlin Radoslavov49e159a2014-10-29 16:22:13 -070024import java.util.Objects;
Pavlin Radoslavovd0e32d72014-10-31 18:11:43 -070025
26import com.google.common.net.InetAddresses;
27import com.google.common.primitives.UnsignedBytes;
28
29import static com.google.common.base.Preconditions.checkState;
Jonathan Hartdec62d42014-09-22 15:59:04 -070030
31/**
Pavlin Radoslavov855ea2d2014-10-30 15:32:39 -070032 * A class representing an IP address.
Pavlin Radoslavovf182f012014-11-04 15:03:18 -080033 * This class is immutable.
Jonathan Hartdec62d42014-09-22 15:59:04 -070034 */
Pavlin Radoslavovf182f012014-11-04 15:03:18 -080035public class IpAddress implements Comparable<IpAddress> {
Pavlin Radoslavov52307e62014-10-29 15:07:37 -070036 // IP Versions
Jonathan Hartdec62d42014-09-22 15:59:04 -070037 public enum Version { INET, INET6 };
38
Pavlin Radoslavov52307e62014-10-29 15:07:37 -070039 // lengths of address, in bytes
40 public static final int INET_BYTE_LENGTH = 4;
41 public static final int INET_BIT_LENGTH = INET_BYTE_LENGTH * Byte.SIZE;
42 public static final int INET6_BYTE_LENGTH = 16;
43 public static final int INET6_BIT_LENGTH = INET6_BYTE_LENGTH * Byte.SIZE;
Jonathan Hartdec62d42014-09-22 15:59:04 -070044
Pavlin Radoslavov52307e62014-10-29 15:07:37 -070045 private final Version version;
46 private final byte[] octets;
Jonathan Hartdec62d42014-09-22 15:59:04 -070047
48 /**
Pavlin Radoslavov52307e62014-10-29 15:07:37 -070049 * Constructor for given IP address version and address octets.
50 *
Pavlin Radoslavovd0e32d72014-10-31 18:11:43 -070051 * @param version the IP address version
Pavlin Radoslavov49e159a2014-10-29 16:22:13 -070052 * @param value the IP address value stored in network byte order
Pavlin Radoslavov52307e62014-10-29 15:07:37 -070053 * (i.e., the most significant byte first)
Pavlin Radoslavovd0e32d72014-10-31 18:11:43 -070054 * @throws IllegalArgumentException if the arguments are invalid
Jonathan Hartdec62d42014-09-22 15:59:04 -070055 */
Pavlin Radoslavovf182f012014-11-04 15:03:18 -080056 protected IpAddress(Version version, byte[] value) {
Pavlin Radoslavovd0e32d72014-10-31 18:11:43 -070057 checkArguments(version, value, 0);
Pavlin Radoslavov49e159a2014-10-29 16:22:13 -070058 this.version = version;
Pavlin Radoslavovd0e32d72014-10-31 18:11:43 -070059 switch (version) {
60 case INET:
61 this.octets = Arrays.copyOf(value, INET_BYTE_LENGTH);
62 break;
63 case INET6:
64 this.octets = Arrays.copyOf(value, INET6_BYTE_LENGTH);
65 break;
66 default:
67 // Should not be reached
68 this.octets = null;
69 break;
Pavlin Radoslavov49e159a2014-10-29 16:22:13 -070070 }
Jonathan Hartdec62d42014-09-22 15:59:04 -070071 }
72
73 /**
74 * Returns the IP version of this address.
75 *
76 * @return the version
77 */
78 public Version version() {
79 return this.version;
80 }
81
82 /**
Pavlin Radoslavov34c81642014-11-04 16:21:38 -080083 * Gets the {@link Ip4Address} view of the IP address.
84 *
85 * @return the {@link Ip4Address} view of the IP address if it is IPv4,
86 * otherwise null
87 */
88 public Ip4Address getIp4Address() {
89 if (version() != Ip4Address.VERSION) {
90 return null;
91 }
92
93 // Return this object itself if it is already instance of Ip4Address
94 if (this instanceof Ip4Address) {
95 return (Ip4Address) this;
96 }
97 return Ip4Address.valueOf(octets);
98 }
99
100 /**
101 * Gets the {@link Ip6Address} view of the IP address.
102 *
103 * @return the {@link Ip6Address} view of the IP address if it is IPv6,
104 * otherwise null
105 */
106 public Ip6Address getIp6Address() {
107 if (version() != Ip6Address.VERSION) {
108 return null;
109 }
110
111 // Return this object itself if it is already instance of Ip6Address
112 if (this instanceof Ip6Address) {
113 return (Ip6Address) this;
114 }
115 return Ip6Address.valueOf(octets);
116 }
117
118 /**
Jonathan Hartdec62d42014-09-22 15:59:04 -0700119 * Returns the IP address as a byte array.
120 *
121 * @return a byte array
122 */
123 public byte[] toOctets() {
Pavlin Radoslavovd0e32d72014-10-31 18:11:43 -0700124 return Arrays.copyOf(octets, octets.length);
Jonathan Hartdec62d42014-09-22 15:59:04 -0700125 }
126
127 /**
Pavlin Radoslavovd0e32d72014-10-31 18:11:43 -0700128 * Computes the IP address byte length for a given IP version.
129 *
130 * @param version the IP version
131 * @return the IP address byte length for the IP version
132 * @throws IllegalArgumentException if the IP version is invalid
133 */
134 public static int byteLength(Version version) {
135 switch (version) {
136 case INET:
137 return INET_BYTE_LENGTH;
138 case INET6:
139 return INET6_BYTE_LENGTH;
140 default:
141 String msg = "Invalid IP version " + version;
142 throw new IllegalArgumentException(msg);
143 }
144 }
145
146 /**
147 * Converts an integer into an IPv4 address.
148 *
149 * @param value an integer representing an IPv4 address value
150 * @return an IP address
151 */
152 public static IpAddress valueOf(int value) {
153 byte[] bytes =
154 ByteBuffer.allocate(INET_BYTE_LENGTH).putInt(value).array();
155 return new IpAddress(Version.INET, bytes);
156 }
157
158 /**
159 * Converts a byte array into an IP address.
160 *
161 * @param version the IP address version
162 * @param value the IP address value stored in network byte order
163 * (i.e., the most significant byte first)
164 * @return an IP address
165 * @throws IllegalArgumentException if the arguments are invalid
166 */
167 public static IpAddress valueOf(Version version, byte[] value) {
168 return new IpAddress(version, value);
169 }
170
171 /**
172 * Converts a byte array and a given offset from the beginning of the
173 * array into an IP address.
174 * <p>
175 * The IP address is stored in network byte order (i.e., the most
176 * significant byte first).
177 * </p>
178 * @param version the IP address version
179 * @param value the value to use
180 * @param offset the offset in bytes from the beginning of the byte array
181 * @return an IP address
182 * @throws IllegalArgumentException if the arguments are invalid
183 */
184 public static IpAddress valueOf(Version version, byte[] value,
185 int offset) {
186 checkArguments(version, value, offset);
187 byte[] bc = Arrays.copyOfRange(value, offset, value.length);
188 return IpAddress.valueOf(version, bc);
189 }
190
191 /**
Pavlin Radoslavovaf5ff792014-10-31 20:51:47 -0700192 * Converts an InetAddress into an IP address.
193 *
194 * @param inetAddress the InetAddress value to use
195 * @return an IP address
196 * @throws IllegalArgumentException if the argument is invalid
197 */
198 public static IpAddress valueOf(InetAddress inetAddress) {
199 byte[] bytes = inetAddress.getAddress();
200 if (inetAddress instanceof Inet4Address) {
201 return new IpAddress(Version.INET, bytes);
202 }
203 if (inetAddress instanceof Inet6Address) {
204 return new IpAddress(Version.INET6, bytes);
205 }
206 // Use the number of bytes as a hint
207 if (bytes.length == INET_BYTE_LENGTH) {
208 return new IpAddress(Version.INET, bytes);
209 }
210 if (bytes.length == INET6_BYTE_LENGTH) {
211 return new IpAddress(Version.INET6, bytes);
212 }
213 final String msg = "Unrecognized IP version address string: " +
214 inetAddress.toString();
215 throw new IllegalArgumentException(msg);
216 }
217
218 /**
Pavlin Radoslavovd0e32d72014-10-31 18:11:43 -0700219 * Converts an IPv4 or IPv6 string literal (e.g., "10.2.3.4" or
220 * "1111:2222::8888") into an IP address.
221 *
222 * @param value an IP address value in string form
223 * @return an IP address
224 * @throws IllegalArgumentException if the argument is invalid
225 */
226 public static IpAddress valueOf(String value) {
Pavlin Radoslavovaf5ff792014-10-31 20:51:47 -0700227 InetAddress inetAddress = null;
Pavlin Radoslavovd0e32d72014-10-31 18:11:43 -0700228 try {
Pavlin Radoslavovaf5ff792014-10-31 20:51:47 -0700229 inetAddress = InetAddresses.forString(value);
Pavlin Radoslavovd0e32d72014-10-31 18:11:43 -0700230 } catch (IllegalArgumentException e) {
231 final String msg = "Invalid IP address string: " + value;
232 throw new IllegalArgumentException(msg);
233 }
Pavlin Radoslavovaf5ff792014-10-31 20:51:47 -0700234 return valueOf(inetAddress);
Pavlin Radoslavovd0e32d72014-10-31 18:11:43 -0700235 }
236
237 /**
Pavlin Radoslavov49e159a2014-10-29 16:22:13 -0700238 * Creates an IP network mask prefix.
239 *
Pavlin Radoslavovd0e32d72014-10-31 18:11:43 -0700240 * @param version the IP address version
Pavlin Radoslavov855ea2d2014-10-30 15:32:39 -0700241 * @param prefixLength the length of the mask prefix. Must be in the
Pavlin Radoslavovd0e32d72014-10-31 18:11:43 -0700242 * interval [0, 32] for IPv4, or [0, 128] for IPv6
Pavlin Radoslavov49e159a2014-10-29 16:22:13 -0700243 * @return a new IP address that contains a mask prefix of the
244 * specified length
Pavlin Radoslavovd0e32d72014-10-31 18:11:43 -0700245 * @throws IllegalArgumentException if the arguments are invalid
Pavlin Radoslavov49e159a2014-10-29 16:22:13 -0700246 */
Pavlin Radoslavovd0e32d72014-10-31 18:11:43 -0700247 public static IpAddress makeMaskPrefix(Version version, int prefixLength) {
Pavlin Radoslavovf182f012014-11-04 15:03:18 -0800248 byte[] mask = makeMaskPrefixArray(version, prefixLength);
Pavlin Radoslavovd0e32d72014-10-31 18:11:43 -0700249 return new IpAddress(version, mask);
Pavlin Radoslavov49e159a2014-10-29 16:22:13 -0700250 }
251
252 /**
253 * Creates an IP address by masking it with a network mask of given
254 * mask length.
255 *
Pavlin Radoslavovf182f012014-11-04 15:03:18 -0800256 * @param address the address to mask
Pavlin Radoslavov855ea2d2014-10-30 15:32:39 -0700257 * @param prefixLength the length of the mask prefix. Must be in the
Pavlin Radoslavovd0e32d72014-10-31 18:11:43 -0700258 * interval [0, 32] for IPv4, or [0, 128] for IPv6
Pavlin Radoslavov49e159a2014-10-29 16:22:13 -0700259 * @return a new IP address that is masked with a mask prefix of the
260 * specified length
Pavlin Radoslavovd0e32d72014-10-31 18:11:43 -0700261 * @throws IllegalArgumentException if the prefix length is invalid
Pavlin Radoslavov49e159a2014-10-29 16:22:13 -0700262 */
Pavlin Radoslavovf182f012014-11-04 15:03:18 -0800263 public static IpAddress makeMaskedAddress(final IpAddress address,
Pavlin Radoslavov855ea2d2014-10-30 15:32:39 -0700264 int prefixLength) {
Pavlin Radoslavovf182f012014-11-04 15:03:18 -0800265 // TODO: The code below should go away and replaced with generics
266 if (address instanceof Ip4Address) {
267 Ip4Address ip4a = (Ip4Address) address;
268 return Ip4Address.makeMaskedAddress(ip4a, prefixLength);
269 } else if (address instanceof Ip6Address) {
270 Ip6Address ip6a = (Ip6Address) address;
271 return Ip6Address.makeMaskedAddress(ip6a, prefixLength);
272 } else {
273 byte[] net = makeMaskedAddressArray(address, prefixLength);
274 return IpAddress.valueOf(address.version(), net);
Pavlin Radoslavov49e159a2014-10-29 16:22:13 -0700275 }
Pavlin Radoslavov49e159a2014-10-29 16:22:13 -0700276 }
277
Jonathan Hartdec62d42014-09-22 15:59:04 -0700278 @Override
Jonathan Hartab63aac2014-10-16 08:52:55 -0700279 public int compareTo(IpAddress o) {
Pavlin Radoslavovd0e32d72014-10-31 18:11:43 -0700280 // Compare first the version
281 if (this.version != o.version) {
282 return this.version.compareTo(o.version);
283 }
284
285 // Compare the bytes, one-by-one
286 for (int i = 0; i < this.octets.length; i++) {
287 if (this.octets[i] != o.octets[i]) {
288 return UnsignedBytes.compare(this.octets[i], o.octets[i]);
289 }
290 }
291 return 0; // Equal
Jonathan Hartab63aac2014-10-16 08:52:55 -0700292 }
293
294 @Override
Jonathan Hartdec62d42014-09-22 15:59:04 -0700295 public int hashCode() {
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700296 return Objects.hash(version, Arrays.hashCode(octets));
Jonathan Hartdec62d42014-09-22 15:59:04 -0700297 }
298
299 @Override
300 public boolean equals(Object obj) {
Pavlin Radoslavov855ea2d2014-10-30 15:32:39 -0700301 if (this == obj) {
Jonathan Hartdec62d42014-09-22 15:59:04 -0700302 return true;
303 }
Pavlin Radoslavov50b70672014-11-05 11:22:25 -0800304 if ((obj == null) || (!(obj instanceof IpAddress))) {
Jonathan Hartdec62d42014-09-22 15:59:04 -0700305 return false;
306 }
307 IpAddress other = (IpAddress) obj;
Pavlin Radoslavov49e159a2014-10-29 16:22:13 -0700308 return (version == other.version) &&
309 Arrays.equals(octets, other.octets);
Jonathan Hartdec62d42014-09-22 15:59:04 -0700310 }
311
312 @Override
313 /*
314 * (non-Javadoc)
Pavlin Radoslavovd0e32d72014-10-31 18:11:43 -0700315 * The string representation of the IP address: "x.x.x.x" for IPv4
316 * addresses, or ':' separated string for IPv6 addresses.
Jonathan Hartdec62d42014-09-22 15:59:04 -0700317 *
318 * @see java.lang.Object#toString()
319 */
320 public String toString() {
Pavlin Radoslavovd0e32d72014-10-31 18:11:43 -0700321 InetAddress inetAddr = null;
322 try {
323 inetAddr = InetAddress.getByAddress(octets);
324 } catch (UnknownHostException e) {
325 // Should never happen
326 checkState(false, "Internal error: Ip6Address.toString()");
327 return "[Invalid IP Address]";
Jonathan Hartdec62d42014-09-22 15:59:04 -0700328 }
Pavlin Radoslavovd0e32d72014-10-31 18:11:43 -0700329 return InetAddresses.toAddrString(inetAddr);
330 }
331
332 /**
333 * Gets the IP address name for the IP address version.
334 *
335 * @param version the IP address version
336 * @return the IP address name for the IP address version
337 */
338 private static String addressName(Version version) {
339 switch (version) {
340 case INET:
341 return "IPv4";
342 case INET6:
343 return "IPv6";
344 default:
345 break;
346 }
347 return "UnknownIP(" + version + ")";
348 }
349
350 /**
351 * Checks whether the arguments are valid.
352 *
353 * @param version the IP address version
354 * @param value the IP address value stored in a byte array
355 * @param offset the offset in bytes from the beginning of the byte
356 * array with the address
357 * @throws IllegalArgumentException if any of the arguments is invalid
358 */
Pavlin Radoslavovf182f012014-11-04 15:03:18 -0800359 static void checkArguments(Version version, byte[] value, int offset) {
Pavlin Radoslavovd0e32d72014-10-31 18:11:43 -0700360 // Check the offset and byte array length
361 int addrByteLength = byteLength(version);
362 if ((offset < 0) || (offset + addrByteLength > value.length)) {
363 String msg;
364 if (value.length < addrByteLength) {
365 msg = "Invalid " + addressName(version) +
366 " address array: array length: " + value.length +
367 ". Must be at least " + addrByteLength;
368 } else {
369 msg = "Invalid " + addressName(version) +
370 " address array: array offset: " + offset +
371 ". Must be in the interval [0, " +
372 (value.length - addrByteLength) + "]";
373 }
374 throw new IllegalArgumentException(msg);
375 }
Jonathan Hartdec62d42014-09-22 15:59:04 -0700376 }
Pavlin Radoslavovf182f012014-11-04 15:03:18 -0800377
378 /**
379 * Creates a byte array for IP network mask prefix.
380 *
381 * @param version the IP address version
382 * @param prefixLength the length of the mask prefix. Must be in the
383 * interval [0, 32] for IPv4, or [0, 128] for IPv6
384 * @return a byte array that contains a mask prefix of the
385 * specified length
386 * @throws IllegalArgumentException if the arguments are invalid
387 */
388 static byte[] makeMaskPrefixArray(Version version, int prefixLength) {
389 int addrByteLength = byteLength(version);
390 int addrBitLength = addrByteLength * Byte.SIZE;
391
392 // Verify the prefix length
393 if ((prefixLength < 0) || (prefixLength > addrBitLength)) {
394 final String msg = "Invalid IP prefix length: " + prefixLength +
395 ". Must be in the interval [0, " + addrBitLength + "].";
396 throw new IllegalArgumentException(msg);
397 }
398
399 // Number of bytes and extra bits that should be all 1s
400 int maskBytes = prefixLength / Byte.SIZE;
401 int maskBits = prefixLength % Byte.SIZE;
402 byte[] mask = new byte[addrByteLength];
403
404 // Set the bytes and extra bits to 1s
405 for (int i = 0; i < maskBytes; i++) {
406 mask[i] = (byte) 0xff; // Set mask bytes to 1s
407 }
408 for (int i = maskBytes; i < addrByteLength; i++) {
409 mask[i] = 0; // Set remaining bytes to 0s
410 }
411 if (maskBits > 0) {
412 mask[maskBytes] = (byte) (0xff << (Byte.SIZE - maskBits));
413 }
414 return mask;
415 }
416
417 /**
418 * Creates a byte array that represents an IP address masked with
419 * a network mask of given mask length.
420 *
421 * @param addr the address to mask
422 * @param prefixLength the length of the mask prefix. Must be in the
423 * interval [0, 32] for IPv4, or [0, 128] for IPv6
424 * @return a byte array that represents the IP address masked with
425 * a mask prefix of the specified length
426 * @throws IllegalArgumentException if the prefix length is invalid
427 */
428 static byte[] makeMaskedAddressArray(final IpAddress addr,
429 int prefixLength) {
430 byte[] mask = IpAddress.makeMaskPrefixArray(addr.version(),
431 prefixLength);
432 byte[] net = new byte[mask.length];
433
434 // Mask each byte
435 for (int i = 0; i < net.length; i++) {
436 net[i] = (byte) (addr.octets[i] & mask[i]);
437 }
438 return net;
439 }
Jonathan Hartdec62d42014-09-22 15:59:04 -0700440}