java获取当前主机的所有ip地址

/**
 * 获取本机所有的ipv4地址
  * @return ipv4地址集合
  */
 public static List<String> getIpAddress() {
     List<String> list = new LinkedList<>();
     try {
         Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();
         while (enumeration.hasMoreElements()) {
             NetworkInterface network = enumeration.nextElement();
             Enumeration<InetAddress> addresses = network.getInetAddresses();
             while (addresses.hasMoreElements()) {
                 InetAddress address = (InetAddress) addresses.nextElement();
                 // 如果需要ipv6地址,增加条件 address instanceof Inet6Address
                 if (null != address && (address instanceof Inet4Address)) {
                     list.add(address.getHostAddress());
                 }
             }
         }
     }catch (Exception e){
         logger.error("获取ipV4的地址集合时,发生异常:{}", e.getMessage());
     }
     return list;
 }

运行结果:java获取当前主机的所有ip地址_第1张图片

你可能感兴趣的:(java,java)