1、获取移动网络ip
2、代码
public String getLocalIpAddress() {
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 (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
return inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {
Log.e("get IpAddress fail", ex.toString());
return "";
}
return "";
}
加上权限
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
3、总结
记得
inetAddress instanceof Inet4Address
不要忘记,不然在Android6.0以上系统获取不到ip