1.通过主机名称获取MAC地址
/**
* 获取操作系统名称
*/
public static String getOsName() {
String os = "";
os = System.getProperty("os.name");
return os;
}
/**
* 获取MAC地址
*/
public static String getMACAddress() {
String address = "";
String os = getOsName();
//根据操作系统类型获取MAC地址
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) {
if (line.indexOf("Physical Address") > 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;
}
2.通过远程主机IP地址获取MAC地址
/**
* 获取远程MAC地址
* @return
*/
public static String getRemoteMac(){
HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
return getRemoteMac(request);
}
/**
* 获取远程MAC地址
* @param request
* @return
*/
public static String getRemoteMac(HttpServletRequest request){
String ip = request.getRemoteAddr();
return getMACAddress(ip);
}
/**
* 通过远程IP获取MAC地址
* @param ip 远程IP地址
* @return
*/
public static String getMACAddress(String ip) {
String str = "";
String macAddress = "";
try {
Process p = Runtime.getRuntime().exec("nbtstat -a " + ip);
InputStreamReader ir = new InputStreamReader(p.getInputStream(),"GBK");
LineNumberReader input = new LineNumberReader(ir);
for (int i = 1; i < 100; i++) {
str = input.readLine();
logger.info("nbtstat -a " + ip +"\n mac info:"+str);
if (str != null) {
if (str.indexOf("MAC 地址",1) > -1) {
// 客户端使用的是中文版操作系统
macAddress = str.substring(str.indexOf("MAC 地址") + 9,
str.length());
break;
} else if (str.indexOf("MAC Address",1) > -1) {
// 客户端使用的是英文版操作系统
macAddress = str.substring(
str.indexOf("MAC Address") + 14, str.length());
break;
}
}else{
logger.error("执行 nbtstat -a " + ip + "指令执行失败");
}
}
} catch (IOException e) {
logger.error("=========获取远程mac地址异常=======IOException:", e);
}
return macAddress;
}