標籤:
以下是源碼:
package test; importjava.io.BufferedReader;importjava.io.File;importjava.io.IOException; importjava.io.InputStream; importjava.io.InputStreamReader; importjava.io.LineNumberReader; importjava.util.Date; publicclass Test { public static String getMACAddressWithCMD() { String mac = null; try { Date date1 = new Date(); Process pro = Runtime.getRuntime().exec("cmd.exe /c ipconfig/all"); InputStream is = pro.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8")); String message = br.readLine(); int index = -1; while (message != null) { if ((index = message.indexOf("Physical Address")) > 0) { mac = message.substring(index + 36).trim(); break; } message = br.readLine(); } br.close(); pro.destroy(); Date date2 = new Date(); System.out.println("getMACAddressWithCMD:" + (date2.getTime()-date1.getTime()) + "ms"); } catch (IOException e) { System.out.println("Can‘t get mac address!"); return null; } return mac; } public static String getMACAddressWithIP(String ip) { String str = ""; String macAddress = ""; try { Date date1 = new Date(); String scancmd = "C:\\Windows\\system32\\nbtstat.exe -A ";// 32位系統 File file = new File("C:\\Windows\\SysWOW64"); // 64位系統 if (file.exists()) { scancmd = "C:\\Windows\\sysnative\\nbtstat.exe -A "; } Process p = Runtime.getRuntime().exec(scancmd + ip); InputStreamReader ir = new InputStreamReader(p.getInputStream()); LineNumberReader input = new LineNumberReader(ir); for (int i = 1; i < 100; i++) { str = input.readLine(); if (str != null) { if (str.indexOf("MAC Address") > 1) { macAddress = str.substring( str.indexOf("MAC Address") + 14, str.length()); break; } } } Date date2 = new Date(); System.out.println("getMACAddressWithIP:" + (date2.getTime()-date1.getTime()) + "ms"); } catch (IOException e) { e.printStackTrace(System.out); } return macAddress; } public static void main(String[] args) { System.out.println("MAC Address:" + getMACAddressWithIP("192.168.0.124")); System.out.println("MAC Address:" + getMACAddressWithCMD()); }}
getMACAddressWithCMD執行速度較快,getMACAddressWithIP慢很多。
sysnative 的作用
其實%WINDIR%\SysNative檔案夾是不存在的,它只是64位Windows系統提供的一種重新導向機制。我們已經知道64位Windows通過System32和SysWoW64兩件檔案夾來區分64位和32位的系統檔案,當32位的應用程式嘗試訪問System32檔案夾的時候,系統會自動把它轉到SysWoW64檔案夾,這樣32位應用程式在32位系統和64位系統就都可以運行了,(而不需要為了64位系統而把System32改成SysWoW64)。這樣就出現了一個問題,32位的應用程式怎麼訪問真正的System32檔案夾呢,即存放64位系統檔案的檔案夾?答案就是通過SysNative檔案夾。這個檔案夾並不存在,即在資源管理員中找不到,但當32位的應用程式嘗試訪問這個檔案夾時,64位的Windows會把它重新導向到真正的System32檔案夾,從而提供了一種讓32位應用程式訪問64位系統檔案的方法。具體細節請參考MSDN。
java擷取Mac地址