Android~獲取WiFi MAC地址和IP方法彙總

最近由於項目需求,需要獲取手機WiFi的MAC地址和IP,於是乎網上搜羅了一波。各種版本的都有,各種方法都有,而且安卓6.0以下、6.0~7.0、7.0以上版本差異都很大!在這裏我就集中給歸一下類,方便以後查閱。

1. 歸類

  1. 6.0之前通過WifiManager修改xml權限獲取。
  2. 6.0~7.0讀取系統文件或shell命令獲取。
  3. 7.0以後通過網絡接口驅動wlan0獲取。

2. 推薦使用代碼

安卓是基於linux的,最後推薦使用最後一種方式獲取WiFi的MAC地址和IP:

// 獲取ip地址
public static InetAddress getLocalInetAddress() {
        InetAddress ip = null;
        try {
            //列舉
            Enumeration<NetworkInterface> en_netInterface = NetworkInterface.getNetworkInterfaces();
            while (en_netInterface.hasMoreElements()) {//是否還有元素
                NetworkInterface ni = (NetworkInterface) en_netInterface.nextElement();//得到下一個元素
                Enumeration<InetAddress> en_ip = ni.getInetAddresses();//得到一個ip地址的列舉
                while (en_ip.hasMoreElements()) {
                    ip = en_ip.nextElement();
                    if (!ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1)
                        break;
                    else
                        ip = null;
                }

                if (ip != null) {
                    break;
                }
            }
        } catch (SocketException e) {

            e.printStackTrace();
        }
        return ip;
    }
// 獲取MAC地址
public static String getMacAddr() {
        try {
            List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface nif : all) {
                if (!nif.getName().equalsIgnoreCase("wlan0")) continue;
                byte[] macBytes = nif.getHardwareAddress();
                //nif.getInetAddresses();
                if (macBytes == null) {
                    return "";
                }
                StringBuilder res1 = new StringBuilder();
                for (byte b : macBytes) {
                    res1.append(String.format("%02X:",b));
                }

                if (res1.length() > 0) {
                    res1.deleteCharAt(res1.length() - 1);
                }
                return res1.toString();
            }
        } catch (Exception ex) {
        }
        return "02:00:00:00:00:00";
    }

3. 部分參考代碼

通過shell命令獲取MAC地址:

**
     * 這是使用adb shell命令來獲取mac地址的方式
     * @return
     */
    public static String getMac() {
        String macSerial = null;
        String str = "";
 
        try {
            Process pp = Runtime.getRuntime().exec("cat /sys/class/net/wlan0/address ");
            InputStreamReader ir = new InputStreamReader(pp.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);
 
            for (; null != str; ) {
                str = input.readLine();
                if (str != null) {
                    macSerial = str.trim();// 去空格
                    break;
                }
            }
        } catch (IOException ex) {
            // 賦予默認值
            ex.printStackTrace();
        }
        return macSerial;
    }

通過讀取/sys/class/net/wlan0/address文件獲取

/**
 * Android 6.0(包括) - Android 7.0(不包括)
 * @return
 */
private static String getMacAddress() {
    String WifiAddress = "02:00:00:00:00:00";
    try {
        WifiAddress = new BufferedReader(new FileReader(new File("/sys/class/net/wlan0/address"))).readLine();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return WifiAddress;
}

通過IP地址獲取MAC地址,其實還是通過網絡接口驅動獲取的。

/**
	 * 根據IP地址獲取MAC地址
	 *
	 * @return
	 */
	private static String getLocalMacAddressFromIp() {
		String strMacAddr = null;
		try {
			//獲得IpD地址
			InetAddress ip = getLocalInetAddress();
			byte[] b = NetworkInterface.getByInetAddress(ip).getHardwareAddress();
			StringBuffer buffer = new StringBuffer();
			for (int i = 0; i < b.length; i++) {
				if (i != 0) {
					buffer.append(':');
				}
				String str = Integer.toHexString(b[i] & 0xFF);
				buffer.append(str.length() == 1 ? 0 + str : str);
			}
			strMacAddr = buffer.toString().toUpperCase();
		} catch (Exception e) {
 
		}
 
		return strMacAddr;
	}
 
/**
	 * 獲取移動設備本地IP
	 *
	 * @return
	 */
	private static InetAddress getLocalInetAddress() {
		InetAddress ip = null;
		try {
			//列舉
			Enumeration<NetworkInterface> en_netInterface = NetworkInterface.getNetworkInterfaces();
			while (en_netInterface.hasMoreElements()) {//是否還有元素
				NetworkInterface ni = (NetworkInterface) en_netInterface.nextElement();//得到下一個元素
				Enumeration<InetAddress> en_ip = ni.getInetAddresses();//得到一個ip地址的列舉
				while (en_ip.hasMoreElements()) {
					ip = en_ip.nextElement();
					if (!ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1)
						break;
					else
						ip = null;
				}
 
				if (ip != null) {
					break;
				}
			}
		} catch (SocketException e) {
 
			e.printStackTrace();
		}
		return ip;
	}

一堆參考:

1、Android獲取Mac地址-適配所有版本
2、Android 6.0 和 7.0後獲取Mac地址
3、Android 6.0獲取MAC地址
4、Android獲取Mac地址-兼容6.0及以上系統
5、Android 手機獲取Mac地址的幾種方法
6、Android 獲得設備狀態信息、Mac地址、IP地址
7、android 獲取設備信息的IP地址和Mac地址—親測無誤!!
8、android獲取Mac地址和IP地址

發佈了99 篇原創文章 · 獲贊 185 · 訪問量 21萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章