【备忘】Android获取正在使用网络的IP4地址

public String getLocalIpAddress() {  
        String ipaddress="";
       
        
    try {  
        for (Enumeration<NetworkInterface> en = NetworkInterface  
                .getNetworkInterfaces(); en.hasMoreElements();) {  
            NetworkInterface intf = en.nextElement();  
            for (Enumeration<InetAddress> enumIpAddr = intf  
                    .getInetAddresses(); enumIpAddr.hasMoreElements();) {  
                InetAddress inetAddress = enumIpAddr.nextElement();  
                if (!inetAddress.isLoopbackAddress()&&inetAddress.getAddress().length==4) {  
                        ipaddress=inetAddress.getHostAddress().toString();  
                }  
            }  
        }  
    } catch (SocketException ex) {  
        Log.e("WifiPreference IpAddress", ex.toString());  
    }  
   
    return ipaddress; 
    }

判断条件inetAddress.getAddress().length==4是判断是否是IP4地址,因为4.0会有IP6地址

这方法总觉得太麻烦,不过我试过ConnectivityManager和其它的都没法获得,哪位有简单方法获得的话,可以在评论里写下

原文地址:https://www.cnblogs.com/kagami/p/3040333.html