获取本地IP

public class LocalhostIP {
    //获取本地ip地址,有可能会有多个地址
    public static String getHostIp() {
        Set addrs = new HashSet();
        Enumeration ns = null;
        try {
            ns = NetworkInterface.getNetworkInterfaces();
        } catch (SocketException e) {
            e.printStackTrace();
        }
        while (ns != null && ns.hasMoreElements()) {
            NetworkInterface n = ns.nextElement();
            Enumeration is = n.getInetAddresses();
            while (is.hasMoreElements()) {
                InetAddress i = is.nextElement();
                //过滤掉特殊IP
                if (!i.isLoopbackAddress() && !i.isLinkLocalAddress() && !i.isMulticastAddress()
                        && !isSpecialIp(i.getHostAddress()))
                    addrs.add(i);
            }
        }
        //默认取第一个IP
        return addrs.iterator().next().getHostAddress();
    }

    //特殊IP
    private static boolean isSpecialIp(String ip) {
        return ip.contains(":") || ip.startsWith("127.") || (ip.startsWith("169.254.") || ip.equals("255.255.255.255"));
    }

}

 

你可能感兴趣的:(JAVA)