Fix possible NullPointerException in getNetworkInterfaces

This occurred with non-primary user account.

See #336
This commit is contained in:
emanuele-f 2023-07-20 21:54:29 +02:00
parent efa982c2c6
commit e2c5b81d4f
3 changed files with 25 additions and 9 deletions

View File

@ -269,15 +269,14 @@ public class CaptureService extends VpnService implements Runnable {
// Map network interfaces
mIfIndexToName = new SparseArray<>();
try {
Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces();
while(ifaces.hasMoreElements()) {
NetworkInterface iface = ifaces.nextElement();
Log.d(TAG, "ifidx " + iface.getIndex() + " -> " + iface.getName());
mIfIndexToName.put(iface.getIndex(), iface.getName());
}
} catch (SocketException ignored) {}
Enumeration<NetworkInterface> ifaces = Utils.getNetworkInterfaces();
while(ifaces.hasMoreElements()) {
NetworkInterface iface = ifaces.nextElement();
Log.d(TAG, "ifidx " + iface.getIndex() + " -> " + iface.getName());
mIfIndexToName.put(iface.getIndex(), iface.getName());
}
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Service.CONNECTIVITY_SERVICE);

View File

@ -109,6 +109,7 @@ import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.UnknownHostException;
@ -124,9 +125,11 @@ import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
@ -1681,4 +1684,18 @@ public class Utils {
else
return PrivateDnsMode.DISABLED;
}
public static @NonNull Enumeration<NetworkInterface> getNetworkInterfaces() {
try {
Enumeration<NetworkInterface> ifs = NetworkInterface.getNetworkInterfaces();
if(ifs != null)
return ifs;
} catch (SocketException | NullPointerException e) {
// NullPointerException can be thrown on Android < 31 with virtual interface without a
// parent interface
e.printStackTrace();
}
return Collections.enumeration(new ArrayList<>());
}
}

View File

@ -233,7 +233,7 @@ public class SettingsActivity extends BaseActivity implements PreferenceFragment
values.add("any");
try {
Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces();
Enumeration<NetworkInterface> ifaces = Utils.getNetworkInterfaces();
while (ifaces.hasMoreElements()) {
NetworkInterface iface = ifaces.nextElement();