getHostAddress() returns a reversed ip address
Asked Answered
A

1

7

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

Ayres answered 29/4, 2015 at 7:47 Comment(2)
I did it in my device.Ayres
I think this is an Endianness problem. Have you tried something like this? #1937357. With the ByteBuffer you can change the order of endianness which may be the problemMicmac
A
8

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.

Admire answered 29/4, 2015 at 7:59 Comment(1)
will I still get the ip address even if I connected it to LAN?Skipjack

© 2022 - 2024 — McMap. All rights reserved.