Java学习

java,spring,structs,hibernate,jsf,ireport,jfreechart,jasperreport,tomcat,jboss -----本博客已经搬家了,新的地址是 http://www.javaly.cn 如果有对文章有任何疑问或者有任何不懂的地方,欢迎到www.javaly.cn (Java乐园)指出,我会尽力帮助解决。一起进步

 

利用正则表达式获取网卡的MAC地址

    现在网上有许多用java实现的获取MAC地址的方法,都是利用了windows系统的config命令,但是这些方法都是直接查找config命令的输 出字符串。这种方法对一种语言的windows系统还可以,当在其它语言的系统下运行时,就会出现问题,本文的代码利用正则表达式,使获取MAC地址的程 序能够在多语言环境下运行。

import java.io.*;
import java.util.regex.*;
public class ReadMacByJava
{
private String mPhysicalAddress = "";
private int mPhysicalMacNumber = 0;
private boolean isInit = false;

public ReadMacByJava()
{
}

public void init()
{
try
{
String line;
Process process = Runtime.getRuntime().exec("cmd /c ipconfig /all");
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
Pattern macPattern =
Pattern.compile("([0-9A-Fa-f]{2})(-[0-9A-Fa-f]{2}){5}");
Matcher macMatcher;
boolean result;
while ((line = bufferedReader.readLine()) != null)
{
if ("".equals(line))
continue;
macMatcher = macPattern.matcher(line);
result = macMatcher.find();
if (result)
{
mPhysicalMacNumber++;
if ("".equals(mPhysicalAddress))
mPhysicalAddress = macMatcher.group(0);
else
mPhysicalAddress += ("," + macMatcher.group(0));
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
isInit = true;
}
public String getPhysicalAddress()
{
if (isInit)
return this.mPhysicalAddress;
else
return "Mac is not init.";
}
public int getPhysicalMacNumber()
{
if (isInit)
return this.mPhysicalMacNumber;
else
{
System.out.println("Mac is not init.");
return 0;
}
}
public static void main(String[] args)
{
ReadMacByJava mac = new ReadMacByJava();
mac.init();
System.out.println("MAC "+mac.getPhysicalMacNumber()+" address :"
+ mac.getPhysicalAddress());
}
}
  运行结果:
C:\java>java ReadMacByJava
MAC 1 address :00-40-CA-C9-9F-71


来源:http://www.java3z.com/cwbwebhome/article/article5/5930.html?id=1873

posted on 2008-07-15 16:53 找个美女做老婆 阅读(1086) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航:
 

导航

统计

公告

本blog已经搬到新家了, 新家:www.javaly.cn
 http://www.javaly.cn

常用链接

留言簿(6)

随笔档案

文章档案

搜索

最新评论

阅读排行榜

评论排行榜