Java 获取本地IP地址

    private static String getIpAddress( ){

        String ip = "";
        Collection<InetAddress> colInetAddress =getAllHostAddress();

        for (InetAddress address : colInetAddress) {
            if (!address.isLoopbackAddress() && address.getHostAddress().contains(":") != true)
                ip = ip + address.getHostAddress() + ",";
        }

        return ip;
    }

    public static Collection<InetAddress> getAllHostAddress() {
        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            Collection<InetAddress> addresses = new ArrayList<InetAddress>();

            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = networkInterfaces.nextElement();
                Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
                while (inetAddresses.hasMoreElements()) {
                    InetAddress inetAddress = inetAddresses.nextElement();
                    addresses.add(inetAddress);
                }
            }

            return addresses;
        } catch (SocketException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

 

posted on 2017-05-17 09:59  fupeng  阅读(294)  评论(0编辑  收藏  举报

导航