我想知道 Android 设备的 IP 地址是 Data IP 还是 Wifi IP。
1) 设备首先连接到 3G,现在设备将被分配到网络 IP。
2) 稍后设备连上WIFI,此时设备会被分配到WIFI IP。
3) 任何可以让我们知道 IP 地址是 Wifi IP 地址还是网络 IP 的 Android API?
在 2.3.5 下面使用并且一切正常,但在 4.0.3 ICS 有一些问题..
/**
* Is the IP Address a a Wifi Ip Address.
* @param ipAddr
* @return boolean
*/
public boolean isWifiIp(byte[] ipAddr){
try{
WifiManager mgr = (WifiManager)mCxt.getSystemService(Context.WIFI_SERVICE);
int wifiIP = mgr.getConnectionInfo().getIpAddress();
int reverseWifiIP = Integer.reverseBytes(wifiIP);
int byteArrayToInt = byteArrayToInt(ipAddr,0);
if(byteArrayToInt == wifiIP || byteArrayToInt == reverseWifiIP)
return true;
}catch (Exception e) {
Logger.d(TAG, e);
}
return false;
}
/**
* Convert IP Address in bytes to int value.
* @param arr
* @param offset
* @return int
*/
public static final int byteArrayToInt(byte[] arr, int offset) {
if (arr == null || arr.length - offset < 4)
return -1;
int r0 = (arr[offset] & 0xFF) << 24;
int r1 = (arr[offset + 1] & 0xFF) << 16;
int r2 = (arr[offset + 2] & 0xFF) << 8;
int r3 = arr[offset + 3] & 0xFF;
return r0 + r1 + r2 + r3;
}
/**
* Fetches the IP Address of the Client. There is Delay of 2 Seconds for the API to return.
*/
public String getClientIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if(isWifiIp(inetAddress.getAddress())){
Logger.d(TAG, "-------- Local IP Address; Not Valid: "+inetAddress.getHostAddress());
continue;
}
if (!inetAddress.isLoopbackAddress()) {
String ipAddress = Formatter.formatIpAddress(inetAddress.hashCode());
Logger.d(TAG, "-------- Some Valid IPv4 is ---"+ipAddress);
return ipAddress;
}
}
}
} catch (SocketException ex) {
Logger.e(TAG, ex.toString());
}
return null;
}
请帮忙
4) 当我关闭移动数据网络并打开 Wifi 时,我仍然得到一些有效的 IPv4 地址,这在 2.3.5 及以下版本中是看不到的。
谢谢
最佳答案
您无法根据 IP 地址检测连接类型,因为您的移动网络和家庭 WiFi 网络都可以分配私有(private) IP 地址。
您需要做的是首先检测您是否有移动网络或 WiFi 连接,然后根据该信息获取该连接的 IP 地址。
关于java - Android:如何知道一个IP地址是一个Wifi IP地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10683495/