获取Linux下的IP地址 java代码

/**
 * 获取Linux下的IP地址
 *
 * @return IP地址
 * @throws SocketException
 */
public static String getLinuxLocalIp() throws SocketException {
  String ip = "";
  try {
    for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
        en.hasMoreElements();) {
      NetworkInterface intf = en.nextElement();
      String name = intf.getName();
      if (!name.contains("docker") && !name.contains("lo")) {
        for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses();
            enumIpAddr.hasMoreElements();) {
          InetAddress inetAddress = enumIpAddr.nextElement();
          if (!inetAddress.isLoopbackAddress()) {
            String ipaddress = inetAddress.getHostAddress().toString();
            if (!ipaddress.contains("::") && !ipaddress.contains("0:0:")
                && !ipaddress.contains("fe80")) {
              ip = ipaddress;
            }
          }
        }
      }
    }
  } catch (SocketException ex) {
    System.out.println("获取ip地址异常");
    ex.printStackTrace();
  }
  System.out.println("IP:" + ip);
  return ip;
}

猜你喜欢

转载自www.cnblogs.com/bcydsl/p/10083326.html