From 880e1239c5d82660b5ba46abc5ddf76f08822c69 Mon Sep 17 00:00:00 2001 From: Norman Maurer Date: Tue, 25 Feb 2020 09:34:38 +0100 Subject: [PATCH] NetworkInterface.getByInetAddress() may return null on Android platform (#10056) Motivation: NetworkInterface.getByInetAddress() may return null on Android. This is incorrect by the API but still happens. To help our users we should provide a workaround Modifications: Just return an empty Enumeration when null is returned. Result: Fixes https://github.com/netty/netty/issues/10045 --- .../io/netty/util/internal/SocketUtils.java | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/common/src/main/java/io/netty/util/internal/SocketUtils.java b/common/src/main/java/io/netty/util/internal/SocketUtils.java index 0ac84bb133..02d9896281 100644 --- a/common/src/main/java/io/netty/util/internal/SocketUtils.java +++ b/common/src/main/java/io/netty/util/internal/SocketUtils.java @@ -32,6 +32,7 @@ import java.security.AccessController; import java.security.PrivilegedAction; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; +import java.util.Collections; import java.util.Enumeration; /** @@ -42,9 +43,16 @@ import java.util.Enumeration; */ public final class SocketUtils { + private static final Enumeration EMPTY = Collections.enumeration(Collections.emptyList()); + private SocketUtils() { } + @SuppressWarnings("unchecked") + private static Enumeration empty() { + return (Enumeration) EMPTY; + } + public static void connect(final Socket socket, final SocketAddress remoteAddress, final int timeout) throws IOException { try { @@ -176,12 +184,20 @@ public final class SocketUtils { } public static Enumeration addressesFromNetworkInterface(final NetworkInterface intf) { - return AccessController.doPrivileged(new PrivilegedAction>() { + Enumeration addresses = + AccessController.doPrivileged(new PrivilegedAction>() { @Override public Enumeration run() { return intf.getInetAddresses(); } }); + // Android seems to sometimes return null even if this is not a valid return value by the api docs. + // Just return an empty Enumeration in this case. + // See https://github.com/netty/netty/issues/10045 + if (addresses == null) { + return empty(); + } + return addresses; } @SuppressJava6Requirement(reason = "Usage guarded by java version check")