From f740f45c987253086a08538865206b237c4c1561 Mon Sep 17 00:00:00 2001 From: Carsten Otto Date: Wed, 26 Oct 2022 04:40:36 +0200 Subject: [PATCH] fix(android): return netmask of first IPv4 address (#634) fixes #633 --- .../netinfo/ConnectivityReceiver.java | 23 ++++++++++++------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/android/src/main/java/com/reactnativecommunity/netinfo/ConnectivityReceiver.java b/android/src/main/java/com/reactnativecommunity/netinfo/ConnectivityReceiver.java index 7966b61c..baeff73d 100644 --- a/android/src/main/java/com/reactnativecommunity/netinfo/ConnectivityReceiver.java +++ b/android/src/main/java/com/reactnativecommunity/netinfo/ConnectivityReceiver.java @@ -23,9 +23,11 @@ import java.math.BigInteger; import java.net.Inet4Address; import java.net.InetAddress; +import java.net.InterfaceAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.Enumeration; +import java.util.List; import java.util.Locale; import javax.annotation.Nonnull; @@ -48,13 +50,18 @@ public abstract class ConnectivityReceiver { private static String getSubnet(InetAddress inetAddress) throws SocketException { NetworkInterface netAddress = NetworkInterface.getByInetAddress(inetAddress); - int mask = - 0xffffffff - << (32 - - netAddress - .getInterfaceAddresses() - .get(1) - .getNetworkPrefixLength()); + List addresses = netAddress.getInterfaceAddresses(); + + short networkPrefixLength = 0; + for (InterfaceAddress address : addresses) { + boolean isIpV4 = address.getAddress().getAddress().length == 4; + if (isIpV4) { + networkPrefixLength = address.getNetworkPrefixLength(); + break; + } + } + + int mask = 0xffffffff << (32 - networkPrefixLength); return String.format( Locale.US, "%d.%d.%d.%d", @@ -145,7 +152,7 @@ protected WritableMap createConnectivityEventMap(@Nullable final String requeste // Add the connection state information boolean isConnected = !mConnectionType.equals(ConnectionType.NONE) - && !mConnectionType.equals(ConnectionType.UNKNOWN); + && !mConnectionType.equals(ConnectionType.UNKNOWN); event.putBoolean("isConnected", isConnected); // Add the internet reachable information