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?
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With