leh*_*rer 5 android ipv4 ipv6 android-networking
我遇到了一些关于在 Android 上以编程方式获取IPv4 和 IPv6 地址的讨论。这些其他问题和答案的问题是:
有没有人可以告诉我如何在没有冗长方法的情况下以简短而整洁的方式完成它(如果可能的话)?
小智 5
对于 ipv4,ipv6 你可以使用
public String getIpv4() {
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();
System.out.println("ip1--:" + inetAddress);
System.out.println("ip2--:" + inetAddress.getHostAddress());
if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
String ipaddress = inetAddress.getHostAddress().toString();
return ipaddress;
}
}
}
} catch (Exception ex) {
Log.e("IP Address", ex.toString());
}
return null;
}
//ipv6
public String getLocalIpV6() {
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();
System.out.println("ip1--:" + inetAddress);
System.out.println("ip2--:" + inetAddress.getHostAddress());
if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet6Address) {
String ipaddress = inetAddress.getHostAddress().toString();
return ipaddress;
}
}
}
} catch (Exception ex) {
Log.e("IP Address", ex.toString());
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5467 次 |
| 最近记录: |