Android-->最全获取本地IP的方法(Wifi/以太网/3G)

直接上代码

public String getIp() {

    {//获取 Wifi IP的方法

        WifiManager wifiManager = (WifiManager) this
                .getSystemService(Context.WIFI_SERVICE);

        if (wifiManager.isWifiEnabled()
                && wifiManager.getWifiState() == wifiManager.WIFI_STATE_ENABLED) {
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            if (wifiInfo != null) {
                int ipAddress = wifiInfo.getIpAddress();
                if (ipAddress == 0)
                    return "";
                return ((ipAddress & 0xff) + "." + (ipAddress >> 8 & 0xff)
                        + "." + (ipAddress >> 16 & 0xff) + "." + (ipAddress >> 24 & 0xff));
            }
        }
    }

    {//获取 以太网ip 的方法, 需要源码环境编译, 文章后面有下载地址;
        ConnectivityManager connectivityManager = (ConnectivityManager) this
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        LinkProperties properties = connectivityManager
                .getLinkProperties(ConnectivityManager.TYPE_ETHERNET);
        if (properties != null) {
            String ipString = properties.getAddresses().toString();

            Pattern pattern = Pattern.compile("\\d+.\\d+.\\d+.\\d+");
            Matcher matcher = pattern.matcher(ipString);
            if (matcher.find()) {
                return matcher.group();
            }
        }
    }

    {//获取 3G网络 ip的方法
        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()) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException ex) {
            ex.printStackTrace();
        }
    }
    return "";

}

注意: 获取不同设备网络环境的IP,请使用不同的方法, 不可通用;请使用上面对应的获取方法;

源码环境下载地址–> 点击下载class4.2

至此: 文章就结束了,如有疑问: QQ群:274306954 欢迎您的加入.

你可能感兴趣的:(android,方法,IP,wifi,以太网)