package com.chenyang.nse.bussiness.tools.net;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

public class IpAddressTool {
   public static List getLinuxLocalIp() throws SocketException {
      List<String> ipList = new ArrayList();
      String ip = "";

      try {
         Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();

         while(en.hasMoreElements()) {
            NetworkInterface intf = (NetworkInterface)en.nextElement();
            String name = intf.getName();
            if (!name.contains("docker") && !name.contains("lo")) {
               Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses();

               while(enumIpAddr.hasMoreElements()) {
                  InetAddress inetAddress = (InetAddress)enumIpAddr.nextElement();
                  if (!inetAddress.isLoopbackAddress()) {
                     String ipaddress = inetAddress.getHostAddress().toString();
                     if (!ipaddress.contains("::") && !ipaddress.contains("0:0:") && !ipaddress.contains("fe80")) {
                        ipList.add(ipaddress);
                     }
                  }
               }
            }
         }
      } catch (SocketException ex) {
         ip = "127.0.0.1";
         ex.printStackTrace();
      }

      return ipList;
   }

   public static void main(String[] args) {
      try {
         String curIpNew = (String)getLinuxLocalIp().get(0);
         System.out.println("curIpNew:" + curIpNew);
      } catch (SocketException e) {
         e.printStackTrace();
      }

   }
}
