使用Java获取本机IPV4地址
public static String getLocalIpv4Address() throws SocketException {
Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces();
String siteLocalAddress = null;
while (ifaces.hasMoreElements()) {
NetworkInterface iface = ifaces.nextElement();
Enumeration<InetAddress> addresses = iface.getInetAddresses();
while (addresses.hasMoreElements()) {
InetAddress addr = addresses.nextElement();
String hostAddress = addr.getHostAddress();
if (addr instanceof Inet4Address
&& !addr.isLoopbackAddress()
&& !hostAddress.startsWith("192.168")
&& !hostAddress.startsWith("172.")
&& !hostAddress.startsWith("169.")) {
if (addr.isSiteLocalAddress()) {
siteLocalAddress = hostAddress;
} else {
return hostAddress;
}
}
}
}
return siteLocalAddress == null ? "" : siteLocalAddress;
}
本文标题:使用Java获取本机IPV4地址
本文链接:https://www.haomeiwen.com/subject/yrkehqtx.html
网友评论