getHostAddress() returns a reversed ip address

走远了吗. 提交于 2019-12-12 08:35:47

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/29937433/gethostaddress-returns-a-reversed-ip-address

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!