為了專案的安全性,有時需要取得電腦的唯一識別碼,最常見的就是網卡的 MAC 位址。以下把專案裡實際使用的工具類整理出來,它會依執行環境自動在 Windows、Windows 7 以上與 Unix/Linux 三種取址方式之間切換。
對外只暴露一個 getMACAddress():先嘗試傳統 Windows 的 ipconfig /all 解析,失敗則改用 NetworkInterface 的純 Java 方式,再失敗才退回 Linux 的 ifconfig 解析。取到之後統一移除分隔符號「-」並轉小寫;三種方式都拿不到時回傳一組預設字串,方便上層做容錯判斷。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
public class MacAddressAPI {
/** 取得目前作業系統名稱,例如 windows xp、linux */
public static String getOSName() {
return System.getProperty("os.name").toLowerCase();
}
/** 取得 unix 網卡的 MAC 位址,非 windows 系統預設走這支 */
public static String getUnixMACAddress() {
String mac = null;
BufferedReader bufferedReader = null;
Process process = null;
try {
// linux 下一般取 eth0 作為主網卡
process = Runtime.getRuntime().exec("ifconfig eth0");
bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
int index = -1;
while ((line = bufferedReader.readLine()) != null) {
index = line.toLowerCase().indexOf("hwaddr");
if (index >= 0) {
mac = line.substring(index + "hwaddr".length() + 1).trim();
break;
}
}
} catch (IOException e) {
System.out.println("unix/linux 方式未取到網卡位址");
} finally {
try {
if (bufferedReader != null) {
bufferedReader.close();
}
} catch (IOException e1) {
e1.printStackTrace();
}
bufferedReader = null;
process = null;
}
return mac;
}
/** 取得 windows 網卡的 MAC 位址 */
public static String getWindowsMACAddress() {
String mac = null;
BufferedReader bufferedReader = null;
Process process = null;
try {
process = Runtime.getRuntime().exec("ipconfig /all");
bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
int index = -1;
while ((line = bufferedReader.readLine()) != null) {
index = line.toLowerCase().indexOf("physical address");
if (index >= 0) {
index = line.indexOf(":");
if (index >= 0) {
mac = line.substring(index + 1).trim();
}
break;
}
}
} catch (IOException e) {
System.out.println("windows 方式未取到網卡位址");
} finally {
try {
if (bufferedReader != null) {
bufferedReader.close();
}
} catch (IOException e1) {
e1.printStackTrace();
}
bufferedReader = null;
process = null;
}
return mac;
}
/** windows 7 專用:走 JDK 原生 API */
public static String getWindows7MACAddress() {
StringBuffer sb = new StringBuffer();
try {
InetAddress ia = InetAddress.getLocalHost();
// 網卡位址存在 byte 陣列中
byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
for (int i = 0; i < mac.length; i++) {
// & 0xFF 是為了把 byte 轉成正整數
String s = Integer.toHexString(mac[i] & 0xFF);
sb.append(s.length() == 1 ? 0 + s : s);
}
} catch (Exception ex) {
System.out.println("windows 7 方式未取到網卡位址");
}
return sb.toString();
}
/** 對外統一入口 */
public static String getMACAddress() {
String mac = getWindowsMACAddress();
if (isNull(mac)) {
mac = getWindows7MACAddress();
}
if (isNull(mac)) {
mac = getUnixMACAddress();
}
if (!isNull(mac)) {
mac = mac.replace("-", "");
} else {
mac = "ABCDEFGHIJ";
}
return mac.toLowerCase();
}
public static boolean isNull(Object strData) {
if (strData == null || String.valueOf(strData).trim().equals("")) {
return true;
}
return false;
}
public static void main(String[] args) {
System.out.println(getWindows7MACAddress());
}
}
getWindowsMACAddress() 依賴外部命令 ipconfig /all,靠字串比對 "physical address" 定位,缺點是不同語言版本的 Windows 輸出標籤不同,容易失效。getWindows7MACAddress() 使用 InetAddress 搭配 NetworkInterface.getHardwareAddress(),跨平台且不受語系影響,是三者中最可靠的做法。getUnixMACAddress() 則解析 ifconfig 輸出中的 hwaddr 欄位,遇到新版 Linux 改用 ip addr 或網卡名稱不是 eth0 時需要自行擴充。
另外提醒兩點:MAC 位址並非絕對唯一,可被修改或偽造,正式環境做授權時建議搭配其他硬體指紋;若機器有多張網卡,NetworkInterface 版本可以透過列舉所有介面來挑選真正要用的那張。