android 获取手机ip地址,3g网络和wifi网络都有效,亲测。
/**
* 网络状态改变后,查询ip,过滤出ipv4
* @return ipv4地址
* @throws SocketException
*/
public String getIpAddress() throws SocketException{
String ipaddress = "";
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 (!inetAddress.isLoopbackAddress()) {
ipaddress = inetAddress.getHostAddress().toString();
//过滤掉ipv6
if(!ipaddress.contains("::")){//ipV6的地址
return ipaddress ;
}
}
}
}
return ipaddress;
}