Android API-23: InetAddressUtils replacement

android, android-6.0-marshmallow, android-networking

Solution

Like I interprete from the comments you can replace that function with this comparison:

inetAddress instanceof Inet4Address

so your code would end in:

if(!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {

Update from 2020 Keep in mind that your user can also have IPv6 enabled. In that case you need to check for `Inet6Address` too.

Problem

Switching to Android Marshmallow API, I was using `org.apache.http.conn.util.InetAddressUtils` for `InetAddressUtils.isIPv4Address(ipAddress)` in a code to list all IPs from a device. As part of the API-23 changes, the `InetAddressUtils` class is now gone. How can I replace the below code now? ``` public static String ipAddress() { try { for (final Enumeration<NetworkInterface> enumerationNetworkInterface = NetworkInterface.getNetworkInterfaces(); enumerationNetworkInterface.hasMoreElements();) { final NetworkInterface networkInterface = enumerationNetworkInterface.nextElement(); for (Enumeration<InetAddress> enumerationInetAddress = networkInterface.getInetAddresses(); enumerationInetAddress.hasMoreElements();) { final InetAddress inetAddress = enumerationInetAddress.nextElement(); final String ipAddress = inetAddress.getHostAddress(); if (! inetAddress.isLoopbackAddress() && InetAddressUtils.isIPv4Address(ipAddress)) { return ipAddress; } } } return null; } catch (final Exception e) { LogHelper.wtf(null, e); return null; } } ```

Original source