MAC地址获取

来源:互联网 发布:传媒大学网络教育 编辑:程序博客网 时间:2024/06/05 15:03

MAC地址获取法一:

<span style="font-size:18px;">public static String getWireMacAddress() {String s = null;int fileLen = 0;File file = new File("/sys/class/net/eth0/address");try {if (file.exists()) {InputStream iis = new FileInputStream(file);byte[] bs = new byte[1024];int lenght = 0;while ((lenght = iis.read(bs, 0, bs.length)) != -1) {s = new String(bs);fileLen += lenght;}iis.close();}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {if (s == null) {return "00:00:00:00:00:00";} else {if (s.contains(":")) {s = s.replace(":", "");}return s.substring(0, fileLen).trim();}}}</span>
法二:

public static String getLocalEthernetMacAddress() {String mac = null;try {Enumeration localEnumeration = NetworkInterface.getNetworkInterfaces();while (localEnumeration.hasMoreElements()) {NetworkInterface localNetworkInterface = (NetworkInterface) localEnumeration.nextElement();String interfaceName = localNetworkInterface.getDisplayName();if (interfaceName == null) {continue;}if (interfaceName.equals("eth0")) {// MACAddr = convertMac(localNetworkInterface// .getHardwareAddress());mac = convertToMac(localNetworkInterface.getHardwareAddress());if (mac != null && mac.startsWith("0:")) {mac = "0" + mac;}break;}}} catch (SocketException e) {e.printStackTrace();}String mac1 = mac.replaceAll(":", "");Log.v("zhang", "+++++" + mac1);return mac1;}private static String convertToMac(byte[] mac) {StringBuilder sb = new StringBuilder();for (int i = 0; i < mac.length; i++) {byte b = mac[i];int value = 0;if (b >= 0 && b <= 16) {value = b;sb.append(Integer.toHexString(value));} else if (b > 16) {value = b;sb.append(Integer.toHexString(value));} else {value = 256 + b;sb.append(Integer.toHexString(value));}if (i != mac.length - 1) {sb.append(":");}}return sb.toString();}



0 0
原创粉丝点击