Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Formatter.formatIPAddress deprecation with API 12

Tags:

android

I see that the method is deprecated and the replacement is supposed to be getHostAddress().

My question is how is getHostAddress a replacement? I can't seem to get it to do anything near the same thing.

What I'm trying to do is take an integer representation of a subnet mask and convert it to a string.

formatIPAddress does this perfectly.

As an example, my subnet mask is "255.255.255.192". The integer value that the WifiManager returns is 105696409. formatIPAddress returns this correctly.

I can't seem to get getHostAddress to even work, much less convert an integer value to a subnet mask string.

Example code that does work

WifiManager wm = (WifiManager) MasterController.maincontext.getSystemService(Context.WIFI_SERVICE);

DhcpInfo wi = wm.getDhcpInfo();


int ip = wm.getDhcpInfo().ipAddress;
int gateway = wm.getDhcpInfo().gateway;
int mask = wm.getDhcpInfo().netmask;

String maskk = Formatter.formatIpAddress(mask);

Anyone have any experience with this? I can get the source code from the formatter class and just use it. But I'd like to just use the new method.

like image 663
Anthony Womack Avatar asked Jun 12 '13 00:06

Anthony Womack


2 Answers

You have to convert the int to byte[], and then using that array to instance InetAddress:

...
int ipAddressInt = wm.getDhcpInfo().netmask;
byte[] ipAddress = BigInteger.valueOf(ipAddressInt).toByteArray();
InetAddress myaddr = InetAddress.getByAddress(ipAddress);
String hostaddr = myaddr.getHostAddress(); // numeric representation (such as "127.0.0.1")

Now I see that the formatter expects little-endian and bigInteger.toByteArray() returns a big-endian representation, so the byte[] should be reversed.

like image 172
DNax Avatar answered Sep 28 '22 05:09

DNax


You could use String.format making a byte mask for each octet:

...
int ipAddress = wm.getDhcpInfo().netmask;
String addressAsString = String.format(Locale.US, "%d.%d.%d.%d",
                            (ipAddress & 0xff),
                            (ipAddress >> 8 & 0xff),
                            (ipAddress >> 16 & 0xff),
                            (ipAddress >> 24 & 0xff));
like image 34
Jaime Marín Avatar answered Sep 28 '22 03:09

Jaime Marín