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.
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.
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));
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