Java Get local IP address

weixin_34253539發表於2017-04-07
    private InetAddress getLocalIPv4Address() {
        Enumeration<?> interfaces = null;
        try {
            interfaces = NetworkInterface.getNetworkInterfaces();
        } catch (SocketException e) {
            e.printStackTrace();
        }
        InetAddress ip = null;
        if (interfaces != null) {
            while (interfaces.hasMoreElements()) {
                NetworkInterface ni = (NetworkInterface) interfaces.nextElement();
                logger.info("NI: " + ni.getName() + ", " + ni.getDisplayName());
                Enumeration<?> addresses = ni.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    ip = (InetAddress) addresses.nextElement();
                    if (ip != null && (ip instanceof Inet4Address)) {
                        logger.info("IP addr: " + ip.getHostAddress());
                        break;
                    }
                }
            }
        }
        return ip;
    }

相關文章