Home » Android » java – getHostAddress() returns a reversed ip address

java – getHostAddress() returns a reversed ip address

Posted by: admin June 15, 2020 Leave a comment

Questions:

I’m trying to get my cell phone ip address by using WifiManager and WifiInfo classes.

It returns correct ip address reversed.

public String getWifiIpAddress() {
    WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
    WifiInfo wi = wm.getConnectionInfo();

    byte[] ipAddress = BigInteger.valueOf(wi.getIpAddress()).toByteArray();
    try {
        InetAddress myAddr = InetAddress.getByAddress(ipAddress);
        String hostAddr = myAddr.getHostAddress();
        return hostAddr;
    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return "";
}

result : 73.0.168.192

How to&Answers:

Ok, I just saw that your address is reversed! 🙂

It is referred as big/little endian issue, read more about Endianness which is must-to-know for all programmers, specially when doing applications integrations and migrations on different Operating Systems.

Add this after gettting the Connection Info from the Wifi manager.

int ipAddress = wi.getIpAddress();

ipAddress = (ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN)) ? 
                Integer.reverseBytes(ipAddress) : ipAddress;

Then continue your code with toByteArray and getHostAddress etc.