Nit*_*der 5 java android android-networking
我想知道Android设备的IP地址是数据IP还是Wifi IP。
1) 设备首先连接到 3G,现在设备将被分配到网络 IP。
2) 后来设备连接到WIFI,现在设备将被分配到WIFI IP。
3)任何Android API可以让我们知道IP地址是Wifi IP地址还是网络IP?
在 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;
}
Run Code Online (Sandbox Code Playgroud)
请帮忙
4) 当我关闭移动数据网络并且 Wifi 打开时,我仍然得到一些有效的 IPv4 地址,这在 2.3.5 及以下版本中没有看到。
谢谢
找到了窍门..http ://developer.android.com/reference/java/net/NetworkInterface.html#getName()
WiFi 的 getName 将以 wlan.. 开头,使用此验证 WiFi IP。
| 归档时间: |
|
| 查看次数: |
12588 次 |
| 最近记录: |