天天看点

Java 多网域本地IP获取

/**
    * 获取本机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;
    }