以下是源码:
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
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。