I want to know the whether IP address of an Android device is Data IP or Wifi IP.
1) Device as is connected to 3G first, now the Device will be assigned to Network IP.
2) Later Device connected to WIFI , now the Device will be assigned to WIFI IP.
3)Any Android API which will let us know an IP Address is a Wifi IP Address or Network IP??
Was Using below in 2.3.5 and things were fine, but in 4.0.3 ICS has some issues..
/**
* 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;
}
Pls Help
4) When i turn off Mobile Data Network and Wifi Is On,I still get a Some Valid IPv4 Address, which is not seen in 2.3.5 and Below.
Thanks
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…