[Android]获取ip地址

1获取IPV4地址

    public String getLocalIPAddress(){
        String address = "0";
        try {
            Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();
            while(enumeration.hasMoreElements()){
                NetworkInterface networkInterface = enumeration.nextElement();
                Enumeration<InetAddress> enumeration2 = networkInterface.getInetAddresses();
                while(enumeration2.hasMoreElements()){
                    InetAddress inetAddress = enumeration2.nextElement();
                    if(!inetAddress.isLoopbackAddress() && (inetAddress instanceof Inet4Address)){
                        address = inetAddress.getHostAddress().toString();
                        return address;
                    }
                }
            }
        } catch (Exception e) {
            Log.e(TAG, e.getMessage(), e);
        }
        return address;
    }

2获取IPV6地址

    public String getLocalIPAddress(){
        String address = "0";
        try {
            Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();
            while(enumeration.hasMoreElements()){
                NetworkInterface networkInterface = enumeration.nextElement();
                Enumeration<InetAddress> enumeration2 = networkInterface.getInetAddresses();
                while(enumeration2.hasMoreElements()){
                    InetAddress inetAddress = enumeration2.nextElement();
                    if(!inetAddress.isLoopbackAddress()){
                        address = inetAddress.getHostAddress().toString();
                        return address;
                    }
                }
            }
        } catch (Exception e) {
            Log.e(TAG, e.getMessage(), e);
        }
        return address;
    }


本文出自 “JackyAnngo” 博客,请务必保留此出处http://jackyanngo.blog.51cto.com/5263823/1614612

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。