首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

純 Java 實作:在 Windows 環境下讀取 MAC 位址

     編輯:Java 相關知識

引言

Java 跨平台特性雖強,但某些場景(如軟體授權綁定硬體)需取得本機唯一識別碼。MAC 位址是常見選擇。本文示範在 Windows XP/NT/2000 環境下,透過 Runtime.exec() 執行 ipconfig /all,解析輸出流取得 MAC 位址的完整實作。

核心原理

Runtime 類別

每個 Java 應用程式擁有唯一的 Runtime 實例,可透過 Runtime.getRuntime() 取得。其 exec(String command) 方法能啟動子程序並回傳 Process 物件,進而取得標準輸出/輸入流。

Process 類別

Process 封裝原生程序,提供:

  • getInputStream():讀取子程序標準輸出
  • getOutputStream():寫入子程序標準輸入
  • waitFor():等待子程序結束並取得退出碼

實作步驟

  1. 呼叫 Runtime.getRuntime().exec("cmd /c ipconfig /all") 執行指令
  2. 以 BufferedReader 包裝 process.getInputStream() 逐行讀取
  3. 尋找包含 Physical Address 的行(格式如 Physical Address. . . . . . . . . : 00-10-DC-A9-0B-2C)
  4. 擷取冒號後的 MAC 位址字串

完整程式碼

import java.io.*;

public class ReadMac {
    public static String physicalAddress = "read Mac error!";

    public static String checkPhysicalAddress() {
        try {
            String line;
            Process process = Runtime.getRuntime().exec("cmd /c ipconfig /all");
            BufferedReader reader = new BufferedReader(
                new InputStreamReader(process.getInputStream()));

            while ((line = reader.readLine()) != null) {
                // Windows ipconfig /all 輸出中的關鍵字
                if (line.indexOf("Physical Address") != -1) {
                    int colonIndex = line.indexOf(":");
                    if (colonIndex != -1) {
                        physicalAddress = line.substring(colonIndex + 2).trim();
                        break; // 找到第一張網卡的 MAC 即結束
                    }
                }
            }
            process.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return physicalAddress;
    }

    public static void main(String[] args) {
        System.out.println("本機 MAC 位址:" + ReadMac.checkPhysicalAddress());
    }
}

執行結果

程式輸出範例:本機 MAC 位址:00-10-DC-A9-0B-2C

ipconfig /all 輸出範例

程式執行結果

注意事項與擴充

  • 平台相依性:此法依賴 Windows ipconfig 輸出格式。Linux/Mac 需改用 ifconfig 或 ip link 並調整解析邏輯。
  • 多網卡:程式目前取第一筆 Physical Address,實務上可依介面名稱(如乙太網路、Wi-Fi)過濾。
  • 權限:需具備執行系統指令權限,Applet 或受限環境可能拋出 SecurityException。
  • 現代替代方案:Java 6+ 可用 NetworkInterface.getNetworkInterfaces() 以純 Java 跨平台取得 MAC,不需呼叫外部指令,建議優先採用。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved