获取本机IP地址的方法

public class Test {
    public static void main(String[] strings) {
        try {
            InetAddress candidateAddress = null;
            // 遍历所有的网络接口
            for (Enumeration ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements(); ) {
                NetworkInterface iface = (NetworkInterface) ifaces.nextElement();
                // 在所有的接口下再遍历IP
                for (Enumeration inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements(); ) {
                    InetAddress inetAddr = (InetAddress) inetAddrs.nextElement();
                    // 排除loopback类型地址
                    if (!inetAddr.isLoopbackAddress()) {
                        if (inetAddr.isSiteLocalAddress()) {
                            // 如果是site-local地址,就是它了
                            System.out.println(inetAddr);
                        } else if (candidateAddress == null) {
                            // site-local类型的地址未被发现,先记录候选地址
                            candidateAddress = inetAddr;
                            System.out.println("地址记录:" + candidateAddress);
                        }
                    }
                }
            }
            if (candidateAddress != null) {
                System.out.println(candidateAddress);
            }
            // 如果没有发现 non-loopback地址.只能用最次选的方案
            InetAddress jdkSuppliedAddress = InetAddress.getLocalHost();
            System.out.println(jdkSuppliedAddress);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}

 

posted @ 2019-01-08 11:20  技术博客这里开始  Views(426)  Comments(0Edit  收藏  举报