Android 获取设备IP,已连接WiFi信息;(Android API-23: InetAddressUtils 替换)

获取本地IP

public static String getLocalIPAddress() {
    String ip = "";
    try {
        for (Enumeration en = NetworkInterface.getNetworkInterfaces();
            en.hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration enumIpAddr = intf.getInetAddresses();
                enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address){
// Inetaddressutils.isIPv4Address(inetAddress.getHostAddress())) { API 19 以前可用
                    ip = inetAddress.getHostAddress().toString();
                    break;
                }
            }
            if (!TextUtils.isEmpty(ip)) break;
        }
    } catch (Exception e) {
        ip = "";
    }
    return ip;
}

注:判断inteAddress 是否是IPV4时,在API 19 以前可以使用

Inetaddressutils .isIPv4Address(inetAddress.getHostAddress())

而在19以后则需要使用 inetAddress instanceof Inet4Address

已连接wifi信息

/*获取当前设备所连接wifi信息*/
public static String  getMyWifiInfo(Context context){
    String str = "";
    WifiManager mWifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    if (mWifi.isWifiEnabled()) {
       // List scanResults = mWifi.getScanResults();  //getScanResults() 扫描到的当前设备的WiFi列表
        WifiInfo wifiInfo = mWifi.getConnectionInfo();
        String netName = wifiInfo.getSSID(); //获取被连接网络的名称
        String netMac =  wifiInfo.getBSSID(); //获取被连接网络的mac地址
        String localMac = wifiInfo.getMacAddress();// 获得本机的MAC地址
        int loalIP = wifiInfo.getIpAddress();
        int level = wifiInfo.getRssi();
        wifiInfo.getLinkSpeed();
        str = wifiInfo.toString();
    }
    return  str;
    }

你可能感兴趣的:(wifi)