2012-02-07 10:43:00|?次阅读|上传:wustguangh【已有?条评论】发表评论
关键词:Java, 网络通信, 操作系统|来源:唯设编程网
许多程序都通过MAC地址保证软件的唯一性,C#,C++等语言获取MAC地址方法很多很方便,但是JAVA的方法不多见,使用操作系统题提供的批处理命令获取MAC地址是非常方便的,而Java可以方便的运行批处理命令,再通过分析命令执行的结果字符串可以得到对应的MAC地址。本文就以Window和Linus分别进行说明,介绍使用Java获取Windows和Linux系统环境下使用批处理命令得到MAC地址的方法,本机的代码在Windows 7中文旗舰版测试成功。
以windows举例,我们可以在CDM命令窗口通过ipconfig /all得到网络相关的详细信息,linux与之类似,只是我们使用的shell脚本是ifconfig -a,我们可以通过Runtime的getRuntime得到当前运行环境,Runtime的exec可以执行操作系统支持的脚本命令,返回Process变量可以通过getInputStream分析对应的文本内容。
//使用批处理命名得到MAC地址
public static String getMACAddress() {
String address = "";
String os = getOsName();
if (os.startsWith("Windows")) {
try {
String command = "cmd.exe /c ipconfig /all";
Process p = Runtime.getRuntime().exec(command);
BufferedReader br = new BufferedReader(new InputStreamReader(
p.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
//如果操作系统为中文,将下面的字符串改成"物理地址"
//如果操作系统为英文,将下面的字符串改成"Physical Address"
if (line.indexOf("物理地址") > 0) {
int index = line.indexOf(":");
index += 2;
address = line.substring(index);
break;
}
}
br.close();
return address.trim();
} catch (IOException e) {
}
} else if (os.startsWith("Linux")) {
String command = "/bin/sh -c ifconfig -a";
Process p;
try {
p = Runtime.getRuntime().exec(command);
BufferedReader br = new BufferedReader(new InputStreamReader(
p.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
if (line.indexOf("HWaddr") > 0) {
int index = line.indexOf("HWaddr") + "HWaddr".length();
address = line.substring(index);
break;
}
}
br.close();
} catch (IOException e) {
}
}
address = address.trim();
return address;
}
该方法调用了getOsName方法得到操作系统的名称,该方法的代码如下:
/**
* 得到操作系统名称
* @return
*/
public static String getOsName() {
String os = "";
os = System.getProperty("os.name");
return os;
}
获取操作系统相关信息通过System.getProperty完成,除得到操作系统名称之外,还可以得到主机的其它信息,这在后面的文章进行介绍。