Programming Tips - Android: get the *best* IP-Address for a device

Date: 2021nov6 Language: Java OS: Android Keywords: GetIpAddress, programmatically Q. Android: get the *best* IP-Address for a device A. When you enumerate the IP-addresses of a typical Android device you'll see several that aren't so great. So here is some code that assigns a score to each one and returns the best.
import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; public class MyIpAddress { private static class Entry implements Comparable<Entry> { int mScore; InetAddress mInetAddress; Entry(final int score, final InetAddress inetAddress) { mScore = score; mInetAddress = inetAddress; } @Override public int compareTo(Entry another) { // We want the largest score first if (mScore > another.mScore) return -1; if (mScore < another.mScore) return 1; return 0; } } public static InetAddress getMyIpAddress() { ArrayList<Entry> a = new ArrayList<Entry>(); try { for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) { final NetworkInterface intf = en.nextElement(); for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) { final InetAddress inetAddress = enumIpAddr.nextElement(); String strAddress = inetAddress.getHostAddress(); if (strAddress == null) strAddress = ""; int score = 0; if (inetAddress.isLoopbackAddress()) { score += -500; } if (inetAddress instanceof Inet4Address) { score += 100; if (strAddress.startsWith("169.254.")) { // Local link range score += -400; } } else if (inetAddress instanceof Inet6Address) { score += 50; if (strAddress.startsWith("fe80::")) { // Local link range score += -400; } } else { score += -1000; // Unknown protocol! } a.add(new Entry(score, inetAddress)); } } } catch (SocketException ex) { // Handle } if (a.size() == 0) return null; Collections.sort(a); return a.get(0).mInetAddress; } public static String getMyIpAddressAsString() { final InetAddress ip = getMyIpAddress(); if (ip == null) return ""; return ip.getHostAddress(); } }