1、新建一个专门用来得到电脑的MAC地址对象类,然后对其进行调用
MacAddress.java
import java.io.*;
import java.util.*;
import java.util.regex.*;
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<String> getMacAddressList() throws IOException {
ArrayList<String> macAddressList = new ArrayList<String>();
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<String> addressList = getMacAddressList();
if (addressList.isEmpty()) {
return "";
}
return addressList.get(0);
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
public static String[] getMacAddresses() {
try {
return getMacAddressList().toArray(new String[0]);
} catch (IOException e) {
e.printStackTrace();
return new String[0];
}
}
}
2、建一个主类对其进行调用
import java.io.IOException;
public class test {
/**
* @param args
*/
public static void main(String[] args) {
MacAddress mac = new MacAddress();
System.out.println("本电脑的MAC地址为:"+mac.getMacAddress());
}
}
any question to call 13886053422 or QQ of 526151410