分享代码片段:java中准确地获取本机ip地址(列表)的方法

原文链接:https://gist.github.com/pfmiles/9f7273b12b4b486e2e9c

package test;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

/**
 * 获取本地ip的工具
 * 
 * @author pf-miles
 * @since 2014-11-25
 */
public class LocalIpAddressUtil {

    /**
     * 获取本地ip地址,有可能会有多个地址, 若有多个网卡则会搜集多个网卡的ip地址
     */
    public static Set resolveLocalAddresses() {
        Set addrs = new HashSet();
        Enumeration ns = null;
        try {
            ns = NetworkInterface.getNetworkInterfaces();
        } catch (SocketException e) {
            // ignored...
        }
        while (ns != null && ns.hasMoreElements()) {
            NetworkInterface n = ns.nextElement();
            Enumeration is = n.getInetAddresses();
            while (is.hasMoreElements()) {
                InetAddress i = is.nextElement();
                if (!i.isLoopbackAddress() && !i.isLinkLocalAddress() && !i.isMulticastAddress()
                    && !isSpecialIp(i.getHostAddress())) addrs.add(i);
            }
        }
        return addrs;
    }

    public static Set resolveLocalIps() {
        Set addrs = resolveLocalAddresses();
        Set ret = new HashSet();
        for (InetAddress addr : addrs)
            ret.add(addr.getHostAddress());
        return ret;
    }

    private static boolean isSpecialIp(String ip) {
        if (ip.contains(":")) return true;
        if (ip.startsWith("127.")) return true;
        if (ip.startsWith("169.254.")) return true;
        if (ip.equals("255.255.255.255")) return true;
        return false;
    }
}

你可能感兴趣的:(ip,java)