JAVA 取得本機mac地址的方法

JAVA中怎樣取得本機的MAC地址,或許windows取得IP地址比較簡單,但是 linux呢? 其實原理是一樣的,都是去讀取輸入流,下面提供了方法,也許比較笨,呵呵! 但是誰有 更好的大家拿出來奉獻一下:
 
 
public static String getWindowsMACAddress() {
    String address = "";
    try {
     ProcessBuilder pb = new ProcessBuilder("ipconfig", "/all");
     Process p = pb.start();
     BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
     String line;
     while ((line = br.readLine()) != null) {
        if (line.indexOf("Physical Address") != -1) {
         int index = line.indexOf(":");
         address = line.substring(index + 1);
         break;
        }
     }
     br.close();
     return address.trim();
    } catch (IOException e) {
    }
    return address;
}
public static String getLinuxMACAddress() {
    String address = "";
    try {
     ProcessBuilder pb = new ProcessBuilder("ifconfig", "-a");
     Process p = pb.start();
     BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
     String line;
     while ((line = br.readLine()) != null) {
        System.out.println(line);
        if (line.indexOf("Link encap:Ethernet    HWaddr") != -1) {
         int index = line.indexOf("HWaddr");
         address = line.substring(index + 7);
         break;
        }
     }
     br.close();
     return address.trim();
    } catch (IOException e) {
    }
    return address;
}
public static String getMACAddress() {
    String address = "";
    String os = System.getProperty("os.name");
    // System.out.println(os);
    if (os != null && os.startsWith("Windows")) {
     address = getWindowsMACAddress();
     address = address.replaceAll("-", ":");
    } else {
     address = getLinuxMACAddress();
    }
    return address;
}
public static void main(String[] args) {
    System.out.println("取得網卡的 Mac 地址" + getMACAddress());
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章