Add android.net.IpPrefix#contains()

This was originally to avoid RuntimeException in RouteInfo#matches():
    When an IPv6 prefix with a length greater than the max permitted
    for IPv4 is matched against an Inet4Address, the call to
    NetworkUtils throws RuntimeException.

Change-Id: I92e2bd19a4e7d656cf682fd27678da07e211850d
This commit is contained in:
Erik Kline 2015-04-13 15:33:34 +09:00
commit b98afb001c
2 changed files with 49 additions and 7 deletions

View file

@ -169,6 +169,21 @@ public final class IpPrefix implements Parcelable {
return prefixLength;
}
/**
* Determines whether the prefix contains the specified address.
*
* @param address An {@link InetAddress} to test.
* @return {@code true} if the prefix covers the given address.
*/
public boolean contains(InetAddress address) {
byte[] addrBytes = (address == null) ? null : address.getAddress();
if (addrBytes == null || addrBytes.length != this.address.length) {
return false;
}
NetworkUtils.maskRawAddress(addrBytes, prefixLength);
return Arrays.equals(this.address, addrBytes);
}
/**
* Returns a string representation of this {@code IpPrefix}.
*

View file

@ -367,13 +367,7 @@ public final class RouteInfo implements Parcelable {
* @return {@code true} if the destination and prefix length cover the given address.
*/
public boolean matches(InetAddress destination) {
if (destination == null) return false;
// match the route destination and destination with prefix length
InetAddress dstNet = NetworkUtils.getNetworkPart(destination,
mDestination.getPrefixLength());
return mDestination.getAddress().equals(dstNet);
return mDestination.contains(destination);
}
/**