Merge "Move shared methods to NetUtils" am: ac148e6bfe am: 60de0b8a53 am: c1f73982c1
Original change: https://android-review.googlesource.com/c/platform/frameworks/libs/net/+/1571849
MUST ONLY BE SUBMITTED BY AUTOMERGER
Change-Id: Ie594597da2288f5b4b672530d95803cfc6ee5bab
diff --git a/staticlibs/framework/com/android/net/module/util/NetUtils.java b/staticlibs/framework/com/android/net/module/util/NetUtils.java
index 4331b65..f08257a 100644
--- a/staticlibs/framework/com/android/net/module/util/NetUtils.java
+++ b/staticlibs/framework/com/android/net/module/util/NetUtils.java
@@ -23,6 +23,7 @@
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
+import java.net.UnknownHostException;
import java.util.Collection;
/**
@@ -67,4 +68,44 @@
}
return bestRoute;
}
+
+ /**
+ * Get InetAddress masked with prefixLength. Will never return null.
+ * @param address the IP address to mask with
+ * @param prefixLength the prefixLength used to mask the IP
+ */
+ public static InetAddress getNetworkPart(InetAddress address, int prefixLength) {
+ byte[] array = address.getAddress();
+ maskRawAddress(array, prefixLength);
+
+ InetAddress netPart = null;
+ try {
+ netPart = InetAddress.getByAddress(array);
+ } catch (UnknownHostException e) {
+ throw new RuntimeException("getNetworkPart error - " + e.toString());
+ }
+ return netPart;
+ }
+
+ /**
+ * Masks a raw IP address byte array with the specified prefix length.
+ */
+ public static void maskRawAddress(byte[] array, int prefixLength) {
+ if (prefixLength < 0 || prefixLength > array.length * 8) {
+ throw new RuntimeException("IP address with " + array.length
+ + " bytes has invalid prefix length " + prefixLength);
+ }
+
+ int offset = prefixLength / 8;
+ int remainder = prefixLength % 8;
+ byte mask = (byte) (0xFF << (8 - remainder));
+
+ if (offset < array.length) array[offset] = (byte) (array[offset] & mask);
+
+ offset++;
+
+ for (; offset < array.length; offset++) {
+ array[offset] = 0;
+ }
+ }
}