问题描述
我试图用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! :)
它被称为大/小端的问题,阅读更多有关这是必须 - 到知道所有的程序员,在不同操作系统上专门做应用整合和迁移的时候。
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;
然后继续你的code。与toByteArray和getHostAddress等。
Then continue your code with toByteArray and getHostAddress etc.
这篇关于getHostAddress()返回一个反转IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!