Add helper method to translate v4 address pair to clat v6
Add helper method to translate address for the follow up
commit to translate keepalive packets.
Bug: 196453719
Test: atest FrameworksNetTests
Change-Id: I02378125e18d6b527dfbefce5066447856f8cfef
diff --git a/service/src/com/android/server/connectivity/Nat464Xlat.java b/service/src/com/android/server/connectivity/Nat464Xlat.java
index a2df7ab..4f1f871 100644
--- a/service/src/com/android/server/connectivity/Nat464Xlat.java
+++ b/service/src/com/android/server/connectivity/Nat464Xlat.java
@@ -44,7 +44,9 @@
import com.android.server.ConnectivityService;
import java.io.IOException;
+import java.net.Inet4Address;
import java.net.Inet6Address;
+import java.net.UnknownHostException;
import java.util.Objects;
/**
@@ -541,6 +543,34 @@
}
/**
+ * Translate the input v4 address to v6 clat address.
+ */
+ @Nullable
+ public Inet6Address translateV4toV6(@NonNull Inet4Address addr) {
+ // Variables in Nat464Xlat should only be accessed from handler thread.
+ ensureRunningOnHandlerThread();
+ if (!isStarted()) return null;
+
+ return convertv4ToClatv6(mNat64PrefixInUse, addr);
+ }
+
+ @Nullable
+ private static Inet6Address convertv4ToClatv6(
+ @NonNull IpPrefix prefix, @NonNull Inet4Address addr) {
+ final byte[] v6Addr = new byte[16];
+ // Generate a v6 address from Nat64 prefix. Prefix should be 12 bytes long.
+ System.arraycopy(prefix.getAddress().getAddress(), 0, v6Addr, 0, 12);
+ System.arraycopy(addr.getAddress(), 0, v6Addr, 12, 4);
+
+ try {
+ return (Inet6Address) Inet6Address.getByAddress(v6Addr);
+ } catch (UnknownHostException e) {
+ Log.e(TAG, "getByAddress should never throw for a numeric address");
+ return null;
+ }
+ }
+
+ /**
* Get the generated v6 address of clat.
*/
@Nullable
diff --git a/service/src/com/android/server/connectivity/NetworkAgentInfo.java b/service/src/com/android/server/connectivity/NetworkAgentInfo.java
index 56ee117..08c1455 100644
--- a/service/src/com/android/server/connectivity/NetworkAgentInfo.java
+++ b/service/src/com/android/server/connectivity/NetworkAgentInfo.java
@@ -68,6 +68,7 @@
import com.android.server.ConnectivityService;
import java.io.PrintWriter;
+import java.net.Inet4Address;
import java.net.Inet6Address;
import java.time.Instant;
import java.util.ArrayList;
@@ -1042,6 +1043,14 @@
}
/**
+ * Translate the input v4 address to v6 clat address.
+ */
+ @Nullable
+ public Inet6Address translateV4toClatV6(@NonNull Inet4Address addr) {
+ return clatd.translateV4toV6(addr);
+ }
+
+ /**
* Get the NetworkMonitorManager in this NetworkAgentInfo.
*
* <p>This will be null before {@link #onNetworkMonitorCreated(INetworkMonitor)} is called.