博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【Android】获取Mac地址【2】
阅读量:7026 次
发布时间:2019-06-28

本文共 6895 字,大约阅读时间需要 22 分钟。

之前写了有些不够详细,现在贴上一些其他代码,仅供参考。

(1) 调用android 的API: NetworkInterface. getHardwareAddress ()

该API的level为9,只有android 2.3以上才有该接口

geMacFromInetAddress	/**	 * 通过InetAddress获取mac地址	 * @attention InetAddress	 * @return Mac Address	 */	private static String geMacFromInetAddress(Context context){		String mResult = null;		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() && InetAddressUtils.isIPv4Address(inetAddress.getHostAddress())) { Log.i(TAG_NETWORK,"get the ip address(inetAddress): "+inetAddress.getHostAddress().toString()); byte[] b = NetworkInterface.getByInetAddress(inetAddress).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); } mResult = buffer.toString().toUpperCase(); Log.i(TAG_NETWORK,"MAC address geMacFromInetAddress: "+mResult); return mResult; } } } } catch (SocketException ex) { Log.i(TAG_NETWORK,ex.toString()); } return null; }

AndroidManifest.xml    
(2) 调用java 的方法: nbtstat/arp

一般android不支持这两个命令。该方法没有试过。

(3) 调用Android的API: WifiManager

权限:

AndroidManifest.xml

代码:

getMacFromWifi	/**	 * 通过wifiManager获取mac地址	 * @attention Wifi	 * @return Mac Address	 */	private static String getMacFromWifi(Context context){        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);           if (!wifiManager.isWifiEnabled()) {           	wifiManager.setWifiEnabled(true);            }           WifiInfo wifiInfo = wifiManager.getConnectionInfo();               String mResult = wifiInfo.getMacAddress();        Log.i(TAG_NETWORK,"Mac address(wifi): "+mResult);        return mResult;	}

这个是需要设备开通Wifi连接,获取到网卡的MAC地址

另,贴上,判断当前是否为wifi连接方式:

isWifiConnected    //判断当前是否使用wifi连接    private static boolean isWifiConnected(Context context){    	ConnectivityManager cm;    	cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);    	boolean result = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED ? true : false ;    	    	Log.i(TAG_NETWORK,"isWifiConnected: "+result);    	return result;    }

(4) 调用Linux的busybox

getMacFromCallCmd	/**	 * 通过callCmd("busybox ifconfig","HWaddr")获取mac地址	 * @attention 需要设备装有busybox工具	 * @return Mac Address	 */	private static String getMacFromCallCmd(){		String result = "";        result = callCmd("busybox ifconfig","HWaddr");                if(result == null || result.length() <= 0){        	Log.i(TAG_NETWORK,"callCmd returns null or empty");        	return null;        }                //对该行数据进行解析        //例如:eth0      Link encap:Ethernet  HWaddr 00:16:E8:3E:DF:67        if(result.length()>0 && result.contains("HWaddr")==true){        	String Mac = result.substring(result.indexOf("HWaddr")+6, result.length()-1);        	Log.i(TAG_NETWORK,"Mac:"+Mac+" Mac.length: "+Mac.length());          	if(Mac.length()>1){        		Mac = Mac.replaceAll(" ", "");        		result = "";        		        		String[] tmp = Mac.split(":");        		for(int i = 0;i

其他相关函数:

callCmd   public static String callCmd(String cmd,String filter) {           String result = "";           String line = "";           try {        	Process proc = Runtime.getRuntime().exec(cmd);            InputStreamReader is = new InputStreamReader(proc.getInputStream());               BufferedReader br = new BufferedReader (is);                           //执行命令cmd,只取结果中含有filter的这一行            while ((line = br.readLine ()) != null && line.contains(filter)== false) {               	//result += line;            	Log.i("test","line: "+line);            }                        result = line;            Log.i("test","result: "+result);        }           catch(Exception e) {               e.printStackTrace();           }           return result;       }

这个需要设备支持busybox工具。现在发现一些设备是没有安装该工具的,这时使用该方法,会报错。

(5)查询记录了MAC地址的文件“/proc/net/arp”

需要有这个文件,并且记录了相应的内容

getMacFromFile   /**       * get the Mac Address from the file /proc/net/arp     * @param context     * @attention the file /proc/net/arp need exit 	 * @return Mac Address     */    private static String getMacFromFile(Context context){    	String mIP = Config.getIpAddress(context);    	if(mIP == null || mIP.length()<=0)    		return null;    	        List
mResult = readFileLines("/proc/net/arp"); Log.d(TAG_NETWORK,"======= /proc/net/arp ========="); for(int i =0;i
1){ for(int j =1;j
mList = new ArrayList
(); String[] mType = mResult.get(j).split(" "); for(int i =0;i
0) mList.add(mType[i]); } if(mList!=null && mList.size()>4 && mList.get(0).equalsIgnoreCase(mIP)){ String result=""; String[] tmp = mList.get(3).split(":"); for(int i = 0;i

 

readFileLines	 /**     * 以行为单位读取文件,常用于读面向行的格式化文件     */    private static List
readFileLines(String fileName) { File file = new File(fileName); BufferedReader reader = null; String tempString =""; List
mResult = new ArrayList
(); try { Log.i("result","以行为单位读取文件内容,一次读一整行:"); reader = new BufferedReader(new FileReader(file)); while((tempString = reader.readLine())!=null){ mResult.add(tempString); } reader.close(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e1) { } } } return mResult; }

记录了MAC地址的文件“/proc/net/arp”内容大致如下:

IP address       HW type     Flags       HW address            Mask     Device

10.63.253.193    0x1         0x2         00:11:92:06:85:3f     *        eth0
10.63.253.194    0x1         0x2         00:11:92:06:85:3a     *        eth1
10.63.253.195    0x1         0x2         00:11:92:06:85:3b     *        eth2

Done!!睡觉喽~

转载地址:http://ycsxl.baihongyu.com/

你可能感兴趣的文章
linux ip配置
查看>>
Exchange 2016之启动Exchange EAC 性能控制台界面
查看>>
【Android开发】如何实现android和服务器长连接呢?推送消息的原理
查看>>
OpenCV 1.0 在VS2005中编译为静态库所需的设置
查看>>
oracle数据库表空间及权限调整示例
查看>>
漏桶算法 Leaky Bucket (令牌桶算法 Token Bucket)学习笔记
查看>>
ext struts2 上传细节
查看>>
Linux shell getopts 学习
查看>>
容易忘记的linux命令之chattr lsattr 设置隐藏权限与特殊权限的设置
查看>>
我的友情链接
查看>>
js动态增加删除ul节点li
查看>>
[Thinking in Java]之控制执行(Controling Execution)(三)
查看>>
mysql数据库详解
查看>>
keepalived(续一)
查看>>
nagios
查看>>
C++可变参数模板(variadic template)详细介绍及代码举例
查看>>
CentOS 7.4 Tengine安装配置详解(六)
查看>>
高性能WEB开发应用指南
查看>>
根据从数据库中获取到的值控制按钮被选中
查看>>
接口要怎么对?你知道正确的姿势吗
查看>>