How do I get the hosts mac address using Java 5?

Dave picture Dave · Aug 26, 2009 · Viewed 8k times · Source

I know you can do this with Java 6 using java.net.NetworkInterface->getHardwareAddress(). But the environment I am deploying on is restricted to Java 5.

Does anyone know how to do this in Java 5 or earlier? Many thanks.

Answer

butterchicken picture butterchicken · Aug 26, 2009

The standard way in Java 5 was to start a native process to run ipconfig or ifconfig and parse the OutputStream to get your answer.

For example:

private String getMacAddress() throws IOException {
    String command = “ipconfig /all”;
    Process pid = Runtime.getRuntime().exec(command);
    BufferedReader in = new BufferedReader(new InputStreamReader(pid.getInputStream()));
    Pattern p = Pattern.compile(”.*Physical Address.*: (.*)”);
    while (true) {
        String line = in.readLine();
        if (line == null)
            break;
        Matcher m = p.matcher(line);
        if (m.matches()) {
            return m.group(1);
        }
    }
}