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()); }
相關文章
相關標籤/搜索