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 · 访问量 20万+

猜你喜欢

转载自blog.csdn.net/Bluechalk/article/details/87877008