java - 如何从 Java 枚举所有启用的 NIC 卡的 IP 地址?

标签 java networking ip-address

缺少解析ipconfig的输出,有没有人有100%纯java的方法来做到这一点?

最佳答案

这很简单:

try {
  InetAddress localhost = InetAddress.getLocalHost();
  LOG.info(" IP Addr: " + localhost.getHostAddress());
  // Just in case this host has multiple IP addresses....
  InetAddress[] allMyIps = InetAddress.getAllByName(localhost.getCanonicalHostName());
  if (allMyIps != null && allMyIps.length > 1) {
    LOG.info(" Full list of IP addresses:");
    for (int i = 0; i < allMyIps.length; i++) {
      LOG.info("    " + allMyIps[i]);
    }
  }
} catch (UnknownHostException e) {
  LOG.info(" (error retrieving server host name)");
}

try {
  LOG.info("Full list of Network Interfaces:");
  for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
    NetworkInterface intf = en.nextElement();
    LOG.info("    " + intf.getName() + " " + intf.getDisplayName());
    for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
      LOG.info("        " + enumIpAddr.nextElement().toString());
    }
  }
} catch (SocketException e) {
  LOG.info(" (error retrieving network interface list)");
}

关于java - 如何从 Java 枚举所有启用的 NIC 卡的 IP 地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57526218/

相关文章:

windows - 如何在 Windows 上创建虚拟网络接口(interface)?

c# - 部署安全预警

java - 在 apache Camel 中使用 JMS 路由时,事务性客户端和 transacted=true 之间有什么区别?

java - JOptionPane 的工作原理

c# - OWIN自托管如何提示防火墙异常?

Python 列出 HTTP 文件和目录

windows-10 - 如何通过exe文件将连接重定向到特定的外部IP地址

c++ - 比较两个 IPv6 地址及其掩码 (windows)

java - 更改java中的最低有效位(LSB)

java - 从 Java 1.4 升级到 JAVA 6 SE