Question

I'm trying to write a method to get a computer's mac address. Tested it on a few computers:

public String mac() throws UnknownHostException, SocketException {
            InetAddress ip = InetAddress.getLocalHost();
    NetworkInterface network = NetworkInterface.getByInetAddress(ip);
    byte[] mac = network.getHardwareAddress();
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < mac.length; i++) {
        sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" :""));     
    }
            System.out.println("MAC: " + sb.toString());
            return(sb.toString());
}

It does what it's supposed to on computers running JDK 7. However, on JDK 6, the byte[] mac returns null, resulting in a nullPointerException. Anyone got a clue why?

No correct solution

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top