歡迎您光臨本站 註冊首頁

JAVA得到網卡物理地址(Windows和Linux)

←手機掃碼閱讀     火星人 @ 2014-03-09 , reply:0
  在我們在寫程序的過程中,有些時候需要知道一些電腦的硬體信息,比如我們寫一些需要註冊的程序的時候,就需要得到某個電腦特定的信息,一般來說,網卡的物理地址是不會重複的,我們正好可以用它來做為我們識別一台電腦的標誌.那如何得到網卡的物理地址呢?我們可以藉助於ProcessBuilder這個類,這個類是JDK1.5新加的,以前也可以用Runtime.exce這個類.在此我們將演示一下如何在Windows和Linux環境下得到網卡的物理地址.
 
  
/*   * Test.java   *   * Created on 2007-9-27, 9:11:15   *   * To change this template, choose Tools | Templates   * and open the template in the editor.   */      package test2;      import java.io.BufferedReader;   import java.io.IOException;   import java.io.InputStreamReader;   import java.util.Properties;   import java.util.logging.Level;   import java.util.logging.Logger;      /**   *   * @author hadeslee   */   public class Test {      public static String getMACAddress() {      String address = "";   String os = System.getProperty("os.name");   System.out.println(os);   if (os != null) {   if (os.startsWith("Windows")) {   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) {      }   }else if(os.startsWith("Linux")){   try {   ProcessBuilder pb = new ProcessBuilder("ifconfig");   Process p = pb.start();   BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));   String line;   while((line=br.readLine())!=null){   int index=line.indexOf("硬體地址");   if(index!=-1){   address=line.substring(index 4);   break;   }   }   br.close();   return address.trim();   } catch (IOException ex) {   Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);   }      }   }   return address;   }      public static void main(String[] args) {   System.out.println(""   Test.getMACAddress());   }   }


  我們可以看一下1.5新增的ProcessBuilder這個類,這個類比起以前用Runtime.exec來說,要強大一些,它可以指定一個環境 變數,並指定程序運行時的目錄空間,並且也可以得到程序運行時的環境變數.因為ipconfig這個命令已經是system32裡面的,不需要我們另外再設環境變數或者指定程序的運行時目錄空間.我們直接用就可以了,然後得到進程的輸出流,就可以分析出我們所需要的東西了.是不是挺簡單的呢
 
  此程序可以得到windows下和Linux下的網卡地址,不過LINUX要是中文版的,英文版的也一樣,只不過把字替換一下就可以了.這樣我們的程序就有了兩個平台的實現.
 


[火星人 ] JAVA得到網卡物理地址(Windows和Linux)已經有411次圍觀

http://coctec.com/docs/linux/show-post-54088.html