package com.utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MacAddress
{
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 static List getMacAddressList() throws IOException {
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("Unknown operating system: " + os);
}
final Process process = Runtime.getRuntime().exec(command);
// Discard the stderr
new Thread() {
@Override
public void run() {
try {
InputStream errorStream = process.getErrorStream();
while (errorStream.read() != -1) {
}
errorStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
// Extract the MAC addresses from stdout
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
for (String line = null; (line = reader.readLine()) != null;) {
Matcher matcher = macPattern.matcher(line);
if (matcher.matches()) {
//macAddressList.add(matcher.group(1));
macAddressList.add(matcher.group(1).replaceAll("[-:]", ""));
}
}
reader.close();
return macAddressList;
}
public static String getMacAddress() {
try {
List addressList = getMacAddressList();
if (addressList.isEmpty()) {
return "";
}
return addressList.get(0);
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
public static List getMacAddressList2() {
List addressList=new ArrayList();
try {
List temp = getMacAddressList();
addressList=temp;
} catch (IOException e) {
e.printStackTrace();
}
return addressList;
}
public static String[] getMacAddresses() {
try {
return getMacAddressList().toArray(new String[0]);
} catch (IOException e) {
e.printStackTrace();
return new String[0];
}
}
public static void main(String[] args) {
MacAddress mac = new MacAddress();
System.out.println("本电脑的MAC地址为:"+mac.getMacAddress());
}
}