参考修改:https://blog.youkuaiyun.com/yztezhl/article/details/50058263
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ComputerUtil {
public static String getMACAddress(){
String osName = getosName().toLowerCase();
Process p = null;
try{
String separator = "";
if(osName.startsWith("windows")){
p = Runtime.getRuntime().exec("ipconfig /all");
separator = "-";// 不同系统mac地址的链接符号不一样
} else if(osName.startsWith("linux")){
p = Runtime.getRuntime().exec("/sbin/ifconfig -a");
separator = ":";
} else {
throw new UnsupportedOperationException("不支持的操作系统");
}
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
String result = "";
while ((line = br.readLine()) != null) {
result += line;
}
br.close();
return filterMacAddress(getIpAdress(), result, separator);
} catch (IOException e){
e.printStackTrace();
}
return "";
}
public static String filterMacAddress(String ip, String processResult, String separator){
String result = "";
String regExp = "((([0-9,A-F,a-f]{1,2}" + separator + "){1,5})[0-9,A-F,a-f]{1,2})";
Pattern pattern = Pattern.compile(regExp);
Matcher matcher = pattern.matcher(processResult);
while(matcher.find()){
result = matcher.group(1);
if((-1 <= processResult.indexOf(ip)) && (-1 <= processResult.lastIndexOf(result))) {
return result;// 如果有多个IP,只匹配本IP对应的Mac.
}
}
return result;
}
@SuppressWarnings("rawtypes")
public static String getIpAdress(){
String sIP = "";
InetAddress ip = null;
try {
//如果是Windows操作系统
if(isWindowsOS()){
ip = InetAddress.getLocalHost();
return ip.getHostAddress();
} else{// 如果是Linux操作系统
//根据网卡取本机配置的IP
Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces();
while (allNetInterfaces.hasMoreElements()) {
NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
Enumeration addresses = netInterface.getInetAddresses();
while (addresses.hasMoreElements()) {
ip = (InetAddress) addresses.nextElement();
if (ip != null && ip instanceof Inet4Address) {
if(!ip.getHostAddress().startsWith("127.0.0.1")){
return ip.getHostAddress();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return sIP;
}
public static String getosName() {
return System.getProperty("os.name");
}
}