Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative for Formatter.formatIpAddress(int);

Tags:

android

I'd used this code in my application, but the warning says its : "The method formatIpAddress(int) from the type Formatter is deprecated"

android.text.format.Formatter.formatIpAddress(mWifiManager.getConnectionInfo().getIpAddress());

what's the quick fix for this?

like image 921
Protect Life Save Forests Avatar asked Dec 30 '13 19:12

Protect Life Save Forests


4 Answers

The documentation states

Use getHostAddress(), which supports both IPv4 and IPv6 addresses. This method does not support IPv6 addresses.

where getHostAddress() refers to InetAddress.getHostAddress().

However, WifiInfo just has a ipv4 address as an int and AFAIK there's no practical way to convert it to an InetAddress. The deprecation is because the function doesn't support ipv6 but neither does WifiInfo. So I'd say just use formatIpAddress() because it works and add @SuppressWarnings("deprecation") to get rid of the warning.

like image 116
laalto Avatar answered Oct 20 '22 16:10

laalto


WifiInfo wifiinfo = manager.getConnectionInfo();
byte[] myIPAddress = BigInteger.valueOf(wifiinfo.getIpAddress()).toByteArray();
// you must reverse the byte array before conversion. Use Apache's commons library
ArrayUtils.reverse(myIPAddress);
InetAddress myInetIP = InetAddress.getByAddress(myIPAddress);
String myIP = myInetIP.getHostAddress();

So myIP should be what you want.

like image 31
Muhammad Riyaz Avatar answered Oct 20 '22 15:10

Muhammad Riyaz


An alternative to Muhammad Riyaz approach:

String ip = InetAddress.getByAddress(
    ByteBuffer
        .allocate(Integer.BYTES)
        .order(ByteOrder.LITTLE_ENDIAN)
        .putInt(manager.getConnectionInfo().getIpAddress())
        .array()
    ).getHostAddress();

This way you don't have to use Apache's commons library.

like image 9
jpihl Avatar answered Oct 20 '22 15:10

jpihl


it was deprecated from api level 12 in favour of [getHostAdress();][1]. So I suggest to add the suppresswarning annotation and do the following thing:

String myIpString = null;
if (apilevel < 12) {
    myIpString = formatIpAddress(...);
} else {
    myIpString = getHostAdress();
}

you can get the api level of the device this way:

int apiLevel = Integer.valueOf(android.os.Build.VERSION.SDK);
like image 2
Blackbelt Avatar answered Oct 20 '22 16:10

Blackbelt