getHostAddress()返回一个反向的ip地址

Ban*_*ana 8 java android ipv4

我正在尝试使用WifiManager和WifiInfo类获取我的手机IP地址.

它返回正确的IP地址反转.

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 "";
}
Run Code Online (Sandbox Code Playgroud)

结果:73.0.168.192

MrS*_*ind 9

好的,我刚刚看到你的地址被颠倒了!:)

它被称为大/小端序问题,请阅读更多关于Endianness的信息,这是所有程序员必须知道的,特别是在不同操作系统上进行应用程序集成和迁移时.

从Wifi管理器获取连接信息后添加此项.

int ipAddress = wi.getIpAddress();

ipAddress = (ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN)) ? 
                Integer.reverseBytes(ipAddress) : ipAddress;
Run Code Online (Sandbox Code Playgroud)

然后使用toByteArray和getHostAddress等继续您的代码.