现在的位置: 首页 > 综合 > 正文

Android机顶盒取网卡的Mac地址

2013年07月14日 ⁄ 综合 ⁄ 共 1370字 ⁄ 字号 评论关闭

android机顶盒上一般有两个网卡,一个有线一个无线,那么在获取mac地址来唯一标识一台终端的时候取那个呢?经过讨论,取有线的Mac地址。但是当前如果我只用的是wifi呢?怎么取有线网卡的mac地址,经过观察settings里面的源码,发现了获取有线网卡mac地址的方法,即使当前机顶盒连接时wifi,如下:

public String getEth0HW(){
	EthernetManager ethManager = (EthernetManager) getSystemService(Context.ETHERNET_SERVICE);
	String str = ethManager.getEthernetHwaddr(ethManager.getEthernetIfaceName());
	if(null == str){
		str = "null";
	}
	return str ;
}

下面的方法是取当前连接网络的mac地址:

获取当前连接网络的网卡的mac地址
private static String parseByte(byte b) {
		String s = "00" + Integer.toHexString(b)+":";
		return s.substring(s.length() - 3);
}

	/**
	 * 获取当前系统连接网络的网卡的mac地址
	 * @return
	 */
	@SuppressLint("NewApi")
	public static final String getMac() {
		byte[] mac = null;
		StringBuffer sb = new StringBuffer();
		try {
			Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
			while (netInterfaces.hasMoreElements()) {
				NetworkInterface ni = netInterfaces.nextElement();
				Enumeration<InetAddress> address = ni.getInetAddresses();
				
				while (address.hasMoreElements()) {
					InetAddress ip = address.nextElement();
					if (ip.isAnyLocalAddress() || !(ip instanceof Inet4Address) || ip.isLoopbackAddress())
						continue;
					if (ip.isSiteLocalAddress())
						mac = ni.getHardwareAddress();
					else if (!ip.isLinkLocalAddress()) {
						mac = ni.getHardwareAddress();
						break;
					}
				}
			}
		} catch (SocketException e) {
			e.printStackTrace();
		}
		
		if(mac != null){
			for(int i=0 ;i<mac.length ;i++){
				sb.append(parseByte(mac[i]));
			}
			return sb.substring(0, sb.length()-1);
		}else{
			return UpdateService.mDefaultMacAddress;
		}
	}
}

抱歉!评论已关闭.