作者热门文章
- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
切换到 Android Marshmallow API,我在代码中使用 org.apache.http.conn.util.InetAddressUtils
的 InetAddressUtils.isIPv4Address(ipAddress)
来列出所有来自设备的 IP。
作为 API-23 changes 的一部分,InetAddressUtils
类现在消失了。
我现在如何替换下面的代码?
public static String ipAddress() {
try {
for (final Enumeration<NetworkInterface> enumerationNetworkInterface = NetworkInterface.getNetworkInterfaces(); enumerationNetworkInterface.hasMoreElements();) {
final NetworkInterface networkInterface = enumerationNetworkInterface.nextElement();
for (Enumeration<InetAddress> enumerationInetAddress = networkInterface.getInetAddresses(); enumerationInetAddress.hasMoreElements();) {
final InetAddress inetAddress = enumerationInetAddress.nextElement();
final String ipAddress = inetAddress.getHostAddress();
if (! inetAddress.isLoopbackAddress() && InetAddressUtils.isIPv4Address(ipAddress)) {
return ipAddress;
}
}
}
return null;
}
catch (final Exception e) {
LogHelper.wtf(null, e);
return null;
}
}
最佳答案
就像我从评论中解释的那样,您可以用这个比较替换那个函数:
inetAddress instanceof Inet4Address
所以你的代码将以:
结尾if(!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
2020 年更新
请记住,您的用户也可以启用 IPv6。在这种情况下,您也需要检查 Inet6Address
。
关于安卓 API-23 : InetAddressUtils replacement,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32141785/
切换到 Android Marshmallow API,我在代码中使用 org.apache.http.conn.util.InetAddressUtils 的 InetAddressUtils.is
我是一名优秀的程序员,十分优秀!