getHostAddress()返回一个反向的IP地址 [英] getHostAddress() returns a reversed ip address

查看:64
本文介绍了getHostAddress()返回一个反向的IP地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

它返回正确的IP地址.

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 "";
}

结果:73.0.168.192

result : 73.0.168.192

推荐答案

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

Ok, I just saw that your address is reversed! :)

这是个大/小端序问题,请阅读有关 Endianness 的更多信息-了解所有程序员,特别是在不同操作系统上进行应用程序集成和迁移时.

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.

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

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;

然后使用toByteArray和getHostAddress等继续执行代码.

Then continue your code with toByteArray and getHostAddress etc.

这篇关于getHostAddress()返回一个反向的IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆