importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStreamReader;importjava.net.InetAddress;importjava.net.NetworkInterface;importjava.util.ArrayList;importjava.util.Enumeration;importjava.util.List;importcom.tjhq.hqoa.utils.Log4jUtil;importcom.tjhq.hqoa.utils.StringUtil;/*** 与系统相关的一些常用工具方法.
*
*@version1.0.0*/
public classMACUtil {/*** 获取当前操作系统名称. return 操作系统名称 例如:windows xp,linux 等.*/
public staticString getOSName() {return System.getProperty("os.name").toLowerCase();
}/*** 获取unix网卡的mac地址. 非windows的系统默认调用本方法获取. 如果有特殊系统请继续扩充新的取mac地址方法.
*
*@returnmac地址*/
public staticString getMAC_linux() {
String mac= null;
BufferedReader bufferedReader= null;
Process process= null;try{//linux下的命令,一般取eth0作为本地主网卡
process = Runtime.getRuntime().exec("ifconfig eth0");//显示信息中包含有mac地址信息
bufferedReader = new BufferedReader(newInputStreamReader(
process.getInputStream()));
String line= null;int index = -1;while ((line = bufferedReader.readLine()) != null) {//寻找标示字符串[hwaddr]
index = line.toLowerCase().indexOf("hwaddr");if (index >= 0) {//找到了//取出mac地址并去除2边空格
mac = line.substring(index + "hwaddr".length() + 1).trim();break;
}
}
}catch(IOException e) {
Log4jUtil.error("获取mac信息错误",e);
}finally{try{if (bufferedReader != null) {
bufferedReader.close();
}
}catch(IOException e1) {
Log4jUtil.error("获取mac信息错误",e1);
}
bufferedReader= null;
process= null;
}returnmac;
}/*** 获取widnows网卡的mac地址.
*
*@returnmac地址*/
public staticString getMAC_windows() {
InetAddress ip= null;
NetworkInterface ni= null;
List macList = new ArrayList();try{
Enumeration netInterfaces = (Enumeration) NetworkInterface
.getNetworkInterfaces();while(netInterfaces.hasMoreElements()) {
ni=(NetworkInterface) netInterfaces.nextElement();//----------特定情况,可以考虑用ni.getName判断//遍历所有ip
Enumeration ips =ni.getInetAddresses();while(ips.hasMoreElements()) {
ip=(InetAddress) ips.nextElement();if (!ip.isLoopbackAddress() //非127.0.0.1
&&ip.getHostAddress().matches("(\\d{1,3}\\.){3}\\d{1,3}")) {
macList.add(getMacFromBytes(ni.getHardwareAddress()));
}
}
}
}catch(Exception e) {
Log4jUtil.error("获取mac错误", e);
}if (macList.size() > 0) {return macList.get(0);
}else{return "";
}
}private static String getMacFromBytes(byte[] bytes) {
StringBuffer mac= newStringBuffer();bytecurrentByte;boolean first = false;for (byteb : bytes) {if(first) {
mac.append("-");
}
currentByte= (byte) ((b & 240) >> 4);
mac.append(Integer.toHexString(currentByte));
currentByte= (byte) (b & 15);
mac.append(Integer.toHexString(currentByte));
first= true;
}returnmac.toString().toUpperCase();
}public static String getMAC() throwsException {
String os=getOSName();
String mac= "";if (os.startsWith("windows")) {
mac=getMAC_windows();
}else if (os.startsWith("linux")) {
mac=getMAC_linux();
}if(!StringUtil.isNotNullOrBlank(mac)){
mac="null";
}returnmac;
}/*** 测试用的main方法.
*
*@paramargc
* 运行参数.
*@throwsException*/
public static void main(String[] argc) throwsException {
String mac=getMAC();
System.out.println(mac);
}
}