Add two utility methods for IPv4 netmasks.
1. Add a validating method to convert a netmask to a prefix length. 2. Add a function to get the implicit netmask of an IPv4 address. 3. Add a unit test. Bug: 19704592 Change-Id: Icb9f58d3903ea01df9e3720383c9bd5db6dd8f26
This commit is contained in:
parent
7f25a63f06
commit
878a6092f1
1 changed files with 105 additions and 0 deletions
|
|
@ -229,6 +229,25 @@ public class NetworkUtils {
|
|||
return Integer.bitCount(netmask);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert an IPv4 netmask to a prefix length, checking that the netmask is contiguous.
|
||||
* @param netmask as a {@code Inet4Address}.
|
||||
* @return the network prefix length
|
||||
* @throws IllegalArgumentException the specified netmask was not contiguous.
|
||||
* @hide
|
||||
*/
|
||||
public static int netmaskToPrefixLength(Inet4Address netmask) {
|
||||
// inetAddressToInt returns an int in *network* byte order.
|
||||
int i = Integer.reverseBytes(inetAddressToInt(netmask));
|
||||
int prefixLength = Integer.bitCount(i);
|
||||
int trailingZeros = Integer.numberOfTrailingZeros(i);
|
||||
if (trailingZeros != 32 - prefixLength) {
|
||||
throw new IllegalArgumentException("Non-contiguous netmask: " + Integer.toHexString(i));
|
||||
}
|
||||
return prefixLength;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Create an InetAddress from a string where the string must be a standard
|
||||
* representation of a V4 or V6 address. Avoids doing a DNS lookup on failure
|
||||
|
|
@ -308,6 +327,22 @@ public class NetworkUtils {
|
|||
return netPart;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the implicit netmask of an IPv4 address, as was the custom before 1993.
|
||||
*/
|
||||
public static int getImplicitNetmask(Inet4Address address) {
|
||||
int firstByte = address.getAddress()[0] & 0xff; // Convert to an unsigned value.
|
||||
if (firstByte < 128) {
|
||||
return 8;
|
||||
} else if (firstByte < 192) {
|
||||
return 16;
|
||||
} else if (firstByte < 224) {
|
||||
return 24;
|
||||
} else {
|
||||
return 32; // Will likely not end well for other reasons.
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Utility method to parse strings such as "192.0.2.5/24" or "2001:db8::cafe:d00d/64".
|
||||
* @hide
|
||||
|
|
|
|||
Loading…
Reference in a new issue