Showing posts with label Java get MAC address of Computer. Show all posts
Showing posts with label Java get MAC address of Computer. Show all posts

Java get MAC address of Computer

    /**
     * This method get the MAC address of a computer
     *
     * @return string of MAC address of computer
     */
    public static String getMacAddres() {
        String macAddress = "";
        try {
            for (Enumeration<NetworkInterface> enm = NetworkInterface.getNetworkInterfaces(); enm.hasMoreElements();) {
                NetworkInterface network1 = (NetworkInterface) enm.nextElement();
                if (null != network1.getHardwareAddress()) {
                    byte[] mac = new byte[50];

                    mac = network1.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) ? "-" : ""));
                    }

                    macAddress = sb.toString();
                }
            }
        } catch (SocketException e) {
            // e.printStackTrace();
        }

        return macAddress;
    }