Skip to content Skip to sidebar Skip to footer

Android Api-23: Inetaddressutils Replacement

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.

Solution 1:

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.

Solution 2:

Add below to your build.gradle(Module:app) file,

android { useLibrary 'org.apache.http.legacy' }

Solution 3:

I couldn't find something better than converting to Inet4Address or Inet6Address

publicbooleanisValidIp4Address(final String hostName) {
      try {
         returnInet4Address.getByName(hostName) != null;
     } catch (UnknownHostException ex) {
         returnfalse;
     } 
}

publicbooleanisValidIp6Address(final String hostName) {
      try {
         returnInet6Address.getByName(hostName) != null;
     } catch (UnknownHostException ex) {
         returnfalse;
     } 
}

Note, the getHostByName actually does the lookup, which isn't always desirable.

Or, you can get source of InetAddessUtils, which unlike getByName(), doesn't do the lookup, but accepts only dotted addresses. The code is really tiny. It uses regexp classes which are supported by Android. Just remove Immutable annotation which isn't really important, and it will compile!

Solution 4:

To use this library in SDK 23 add following line in project's build.gradle file:

useLibrary 'org.apache.http.legacy'

Solution 5:

Using try catch as logic is horrible practice and should only be done if totally unavoidable..

Use something like this instead:

if (inetAddress instanceof Inet4Address){
    //do something
}  

Post a Comment for "Android Api-23: Inetaddressutils Replacement"