java获取mac地址_java获取Mac地址

以下是源码:

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。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值