private static String macAddressStr = null;
private static String computerName = System.getenv().get("COMPUTERNAME");
private static final String[] windowsCommand = { "ipconfig", "/all" };
private static final String[] linuxCommand = { "/sbin/ifconfig", "-a" };
private static final Pattern macPattern = Pattern.compile(".*((:?[0-9a-f]{2}[-:]){5}[0-9a-f]{2}).*", Pattern.CASE_INSENSITIVE);
private final static List getMacAddressList() throws IOException {
final ArrayList macAddressList = new ArrayList();
final String os = System.getProperty("os.name");
final String command[];
if (os.startsWith("Windows")) {
command = windowsCommand;
}
else if (os.startsWith("Linux")) {
command = linuxCommand;
}
else {
throw new IOException("Unknow operating system:" + os);
}
final Process process = Runtime.getRuntime().exec(command);
BufferedReader bufReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
for (String line = null ; (line = bufReader.readLine()) != null ;) {
Matcher matcher = macPattern.matcher(line);
if (matcher.matches()) {
macAddressList.add(matcher.group(1));
}
}
process.destroy();
bufReader.close();
return macAddressList;
}
public static String getMacAddress() {
if (macAddressStr == null || macAddressStr.equals("")) {
StringBuffer sb = new StringBuffer();
try {
List macList = getMacAddressList();
for (Iterator iter = macList.iterator() ; iter.hasNext() ;) {
String amac = iter.next();
if (!amac.equals("0000000000E0")) {
sb.append(amac);
break;
}
}
}
catch (IOException e) {
e.printStackTrace();
}
macAddressStr = sb.toString();
}
return macAddressStr;
}
public static String getComputerName() {
if (computerName == null || computerName.equals("")) {
computerName = System.getenv().get("COMPUTERNAME");
}
return computerName;
}