发布日期:2023-03-31来源:武汉北大青鸟武汉校区作者:武汉宏鹏
北大青鸟java课程 获取网卡MAC地址及序列号的方法
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.NetworkInterface; import java.net.SocketException; import java.util.Enumeration; public class MACAddress { public MACAddress() { } public static String getMACAddress() { String address = ""; String os = System.getProperty("os.name"); if (os != null && os.startsWith("Windows")) { try { String command = "cmd.exe /c ipconfig /all"; Process p = Runtime.getRuntime().exec(command); BufferedReader br = new BufferedReader(new InputStreamReader(p .getInputStream())); String line; while ((line = br.readLine()) != null) { if (line.indexOf("Physical Address") > 0) { int index = line.indexOf(":"); index += 2; address = line.substring(index); break; } } br.close(); return address.trim(); } catch (IOException e) { } } return address; } public static void main(String[] args) { // System.out.println(""+MACAddress.getMACAddress()); try { // 枚举所有网络接口设备 Enumeration intefaces = NetworkInterface.getNetworkInterfaces(); // 循环处理每一个网络接口设备 while (intefaces.hasMoreElements()) { NetworkInterface face = (NetworkInterface) intefaces .nextElement(); if (face.getName().length() >= 3) { if ((face.getName()).substring(0, 3).equals("eth") || (face.getName()).substring(0, 3).equals("net")) { byte[] mac = face.getHardwareAddress(); if (mac != null && mac.length == 6) { System.out.println("网卡显示名称:" + face.getDisplayName()); System.out.println("网卡设备名称:" + face.getName()); System.out.println("MAC地址:" + bytes2mac(mac)); // break; } } } } } catch (SocketException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private static String bytes2mac(byte[] bytes) { if (bytes.length != 6) { System.out.println("地址错误"); return null; } StringBuffer macString = new StringBuffer(); byte currentByte; for (int i = 0; i < bytes.length; i++) { currentByte = (byte) ((bytes[i] & 240) >> 4); macString.append(Integer.toHexString(currentByte)); currentByte = (byte) (bytes[i] & 15); macString.append(Integer.toHexString(currentByte)); macString.append("-"); } macString.delete(macString.length() - 1, macString.length()); return macString.toString().toUpperCase(); } }
Copyright (c) 2006-2023 武汉宏鹏教育咨询有限公司 版权所有 All Rights Reserved.