2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.controller.sal.utils;
11 import java.net.Inet4Address;
12 import java.net.Inet6Address;
13 import java.net.InetAddress;
14 import java.net.UnknownHostException;
15 import java.util.regex.Matcher;
16 import java.util.regex.Pattern;
18 import org.slf4j.Logger;
19 import org.slf4j.LoggerFactory;
22 * Utility class containing the common utility functions needed for operating on
23 * networking data structures
25 public abstract class NetUtils {
26 protected static final Logger logger = LoggerFactory.getLogger(NetUtils.class);
28 * Constant holding the number of bits in a byte
30 public static final int NumBitsInAByte = 8;
33 * Constant holding the number of bytes in MAC Address
35 public static final int MACAddrLengthInBytes = 6;
38 * Constant holding the number of words in MAC Address
40 public static final int MACAddrLengthInWords = 3;
43 * Constant holding the broadcast MAC address
45 private static final byte[] BroadcastMACAddr = {-1, -1, -1, -1, -1, -1};
48 * Converts a 4 bytes array into an integer number
51 * the 4 bytes long byte array
52 * @return the integer number
54 public static int byteArray4ToInt(byte[] ba) {
55 if (ba == null || ba.length != 4) {
58 return (0xff & ba[0]) << 24 | (0xff & ba[1]) << 16 | (0xff & ba[2]) << 8 | (0xff & ba[3]);
62 * Converts a 6 bytes array into a long number MAC addresses.
65 * The 6 bytes long byte array.
66 * @return The long number.
67 * Zero is returned if {@code ba} is {@code null} or
68 * the length of it is not six.
70 public static long byteArray6ToLong(byte[] ba) {
71 if (ba == null || ba.length != MACAddrLengthInBytes) {
77 num <<= NumBitsInAByte;
80 } while (i < MACAddrLengthInBytes);
85 * Converts a long number to a 6 bytes array for MAC addresses.
89 * @return The byte array.
91 public static byte[] longToByteArray6(long addr){
92 byte[] mac = new byte[MACAddrLengthInBytes];
93 int i = MACAddrLengthInBytes - 1;
96 addr >>>= NumBitsInAByte;
103 * Converts an integer number into a 4 bytes array
107 * @return the byte array
109 public static byte[] intToByteArray4(int i) {
110 return new byte[] { (byte) ((i >> 24) & 0xff), (byte) ((i >> 16) & 0xff), (byte) ((i >> 8) & 0xff),
115 * Converts an IP address passed as integer value into the respective
119 * the IP address in integer form
120 * @return the IP address in InetAddress form
122 public static InetAddress getInetAddress(int address) {
123 InetAddress ip = null;
125 ip = InetAddress.getByAddress(NetUtils.intToByteArray4(address));
126 } catch (UnknownHostException e) {
133 * Return the InetAddress Network Mask given the length of the prefix bit
134 * mask. The prefix bit mask indicates the contiguous leading bits that are
135 * NOT masked out. Example: A prefix bit mask length of 8 will give an
136 * InetAddress Network Mask of 255.0.0.0
138 * @param prefixMaskLength
139 * integer representing the length of the prefix network mask
141 * boolean representing the IP version of the returned address
144 public static InetAddress getInetNetworkMask(int prefixMaskLength, boolean isV6) {
145 if (prefixMaskLength < 0 || (!isV6 && prefixMaskLength > 32) || (isV6 && prefixMaskLength > 128)) {
148 byte v4Address[] = { 0, 0, 0, 0 };
149 byte v6Address[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
150 byte address[] = (isV6) ? v6Address : v4Address;
151 int numBytes = prefixMaskLength / 8;
152 int numBits = prefixMaskLength % 8;
154 for (; i < numBytes; i++) {
155 address[i] = (byte) 0xff;
159 for (int j = 0; j < numBits; j++) {
162 address[i] = (byte) rem;
166 return InetAddress.getByAddress(address);
167 } catch (UnknownHostException e) {
174 * Returns the prefix size in bits of the specified subnet mask. Example:
175 * For the subnet mask ff.ff.ff.e0 it returns 25 while for ff.00.00.00 it
176 * returns 8. If the passed subnetMask array is null, 0 is returned.
179 * the subnet mask as byte array
180 * @return the prefix length as number of bits
182 public static int getSubnetMaskLength(byte[] subnetMask) {
184 if (subnetMask != null && (subnetMask.length == 4 || subnetMask.length == 16)) {
186 while (index < subnetMask.length && subnetMask[index] == (byte) 0xFF) {
187 maskLength += NetUtils.NumBitsInAByte;
190 if (index != subnetMask.length) {
191 int bits = NetUtils.NumBitsInAByte - 1;
192 while (bits >= 0 && (subnetMask[index] & 1 << bits) != 0) {
202 * Returns the prefix size in bits of the specified subnet mask. Example:
203 * For the subnet mask 255.255.255.128 it returns 25 while for 255.0.0.0 it
204 * returns 8. If the passed subnetMask object is null, 0 is returned
207 * the subnet mask as InetAddress
208 * @return the prefix length as number of bits
210 public static int getSubnetMaskLength(InetAddress subnetMask) {
211 return subnetMask == null ? 0 : NetUtils.getSubnetMaskLength(subnetMask.getAddress());
215 * Given an IP address and a prefix network mask length, it returns the
216 * equivalent subnet prefix IP address Example: for ip = "172.28.30.254" and
217 * maskLen = 25 it will return "172.28.30.128"
220 * the IP address in InetAddress form
222 * the length of the prefix network mask
223 * @return the subnet prefix IP address in InetAddress form
225 public static InetAddress getSubnetPrefix(InetAddress ip, int maskLen) {
226 int bytes = maskLen / 8;
227 int bits = maskLen % 8;
229 byte[] sn = ip.getAddress();
231 modifiedByte = (byte) (sn[bytes] >> (8 - bits));
232 sn[bytes] = (byte) (modifiedByte << (8 - bits));
235 for (; bytes < sn.length; bytes++) {
236 sn[bytes] = (byte) (0);
239 return InetAddress.getByAddress(sn);
240 } catch (UnknownHostException e) {
246 * Checks if the test address and mask conflicts with the filter address and
249 * For example: testAddress: 172.28.2.23 testMask: 255.255.255.0
250 * filtAddress: 172.28.1.10 testMask: 255.255.255.0 conflict
252 * testAddress: 172.28.2.23 testMask: 255.255.255.0 filtAddress: 172.28.1.10
253 * testMask: 255.255.0.0 do not conflict
255 * Null parameters are permitted
258 * @param filterAddress
263 public static boolean inetAddressConflict(InetAddress testAddress, InetAddress filterAddress, InetAddress testMask,
264 InetAddress filterMask) {
266 if ((testAddress == null) || (filterAddress == null)) {
271 if (isAny(testAddress) || isAny(filterAddress)) {
275 int testMaskLen = (testMask == null) ? ((testAddress instanceof Inet4Address) ? 32 : 128) : NetUtils
276 .getSubnetMaskLength(testMask);
277 int filterMaskLen = NetUtils.getSubnetMaskLength(filterMask);
279 // Mask length check. Test mask has to be more specific than filter one
280 if (testMaskLen < filterMaskLen) {
284 // Subnet Prefix on filter mask length must be the same
285 InetAddress prefix1 = getSubnetPrefix(testAddress, filterMaskLen);
286 InetAddress prefix2 = getSubnetPrefix(filterAddress, filterMaskLen);
287 return (!prefix1.equals(prefix2));
291 * Returns true if the passed MAC address is all zero
294 * the byte array representing the MAC address
295 * @return true if all MAC bytes are zero
297 public static boolean isZeroMAC(byte[] mac) {
298 for (short i = 0; i < 6; i++) {
307 * Returns true if the MAC address is the broadcast MAC address and false
313 public static boolean isBroadcastMACAddr(byte[] MACAddress) {
314 if (MACAddress.length == MACAddrLengthInBytes) {
315 for (int i = 0; i < 6; i++) {
316 if (MACAddress[i] != BroadcastMACAddr[i]) {
327 * Returns true if the MAC address is a multicast MAC address and false
328 * otherwise. Note that this explicitly returns false for the broadcast MAC
334 public static boolean isMulticastMACAddr(byte[] MACAddress) {
335 if (MACAddress.length == MACAddrLengthInBytes && !isBroadcastMACAddr(MACAddress)) {
336 if (MACAddress[0] % 2 == 1) {
344 * Returns true if the passed InetAddress contains all zero
347 * the IP address to test
348 * @return true if the address is all zero
350 public static boolean isAny(InetAddress ip) {
351 for (byte b : ip.getAddress()) {
359 public static boolean fieldsConflict(int field1, int field2) {
360 if ((field1 == 0) || (field2 == 0) || (field1 == field2)) {
366 public static InetAddress parseInetAddress(String addressString) {
367 InetAddress address = null;
369 address = InetAddress.getByName(addressString);
370 } catch (UnknownHostException e) {
377 * Checks if the passed IP v4 address in string form is valid The address
378 * may specify a mask at the end as "/MM"
381 * the v4 address as A.B.C.D/MM
384 public static boolean isIPv4AddressValid(String cidr) {
389 String values[] = cidr.split("/");
390 Pattern ipv4Pattern = Pattern
391 .compile("(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])");
392 Matcher mm = ipv4Pattern.matcher(values[0]);
396 if (values.length >= 2) {
397 int prefix = Integer.valueOf(values[1]);
398 if ((prefix < 0) || (prefix > 32)) {
406 * Checks if the passed IP v6 address in string form is valid The address
407 * may specify a mask at the end as "/MMM"
410 * the v6 address as A::1/MMM
413 public static boolean isIPv6AddressValid(String cidr) {
418 String values[] = cidr.split("/");
420 // when given an IP address, InetAddress.getByName validates the ip
422 InetAddress addr = InetAddress.getByName(values[0]);
423 if (!(addr instanceof Inet6Address)) {
426 } catch (UnknownHostException ex) {
430 if (values.length >= 2) {
431 int prefix = Integer.valueOf(values[1]);
432 if ((prefix < 0) || (prefix > 128)) {
440 * Checks if the passed IP address in string form is a valid v4 or v6
441 * address. The address may specify a mask at the end as "/MMM"
444 * the v4 or v6 address as IP/MMM
447 public static boolean isIPAddressValid(String cidr) {
448 return NetUtils.isIPv4AddressValid(cidr) || NetUtils.isIPv6AddressValid(cidr);
452 * Following utilities are useful when you need to compare or bit shift java
453 * primitive type variable which are inerently signed
456 * Returns the unsigned value of the passed byte variable
460 * @return the int variable containing the unsigned byte value
462 public static int getUnsignedByte(byte b) {
463 return (b > 0) ? (int) b : (b & 0x7F | 0x80);
467 * Return the unsigned value of the passed short variable
471 * @return the int variable containing the unsigned short value
473 public static int getUnsignedShort(short s) {
474 return (s > 0) ? (int) s : (s & 0x7FFF | 0x8000);
478 * Returns the highest v4 or v6 InetAddress
481 * true for IPv6, false for Ipv4
482 * @return The highest IPv4 or IPv6 address
484 public static InetAddress gethighestIP(boolean v6) {
486 return (v6) ? InetAddress.getByName("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff") : InetAddress
487 .getByName("255.255.255.255");
488 } catch (UnknownHostException e) {