package com.sunbin.test;
import java.io.*;
import java.util.regex.*;
public class ReadMacByJava {
private String mPhysicalAddress = "";
private int mPhysicalMacNumber = 0;
private boolean isInit = false;
public void init() {
try {
String line;
String os = System.getProperty("os.name");
Process process = null;
if (os != null && os.startsWith("Windows")) {
process = Runtime.getRuntime().exec("cmd /c ipconfig /all");
} else {
process = Runtime.getRuntime().exec("ifconfig eth0");
}
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 static void main(String[] args){
ReadMacByJava mac = new ReadMacByJava();
mac.init();
System.out.println("MAC address :"+ mac.getPhysicalAddress());
}
}