/**
* 获取本机IPv4地址<br>
*
* @return 本机IP地址
* @author
* @date 2017年2月24日下午1:46:31
* @since 5.3.6
*/
private static List<String> getLocalIpAddressList() {
List<String> rsList = new ArrayList<>();
try {
Enumeration<NetworkInterface> interfaces = null;
interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface ni = interfaces.nextElement();
Enumeration<InetAddress> addresss = ni.getInetAddresses();
while (addresss.hasMoreElements()) {
InetAddress nextElement = addresss.nextElement();
if (nextElement instanceof Inet4Address)
{
String hostAddress = nextElement.getHostAddress();
logger.info("localhost IPv4 : {}", hostAddress);
rsList.add(hostAddress);
} else if (nextElement instanceof Inet6Address) {
String hostAddress = nextElement.getHostAddress();
logger.info("localhost IPv6 : {}", hostAddress);
}
}
}
} catch (Exception e) {
e.printStackTrace();
logger.error("get localhost fail!");
}
return rsList;
}
本文介绍了一种通过Java程序获取本地计算机IPv4地址的方法。该方法使用NetworkInterface类遍历网络接口,并从每个接口中获取InetAddress实例,进一步筛选出IPv4地址。

被折叠的 条评论
为什么被折叠?



