0

i have the following code to extract MAC Address for my Ubuntu device & i am putting the MAC Address in database. This code works fine In windows PC where as the same doesn't work in Ubuntu Device . The database field gets empty. My Application is a web application. I am taking the war file & putting that in the tomcat server which is there in my Ubuntu device.

 public static String getMACAddress()
  {
    StringBuffer strMac = new StringBuffer();
    try {

        InetAddress address = InetAddress.getLocalHost();
        // InetAddress address = InetAddress.getByName("192.168.46.53");

        /*
         * Get NetworkInterface for the current host and then read the
         * hardware address.
         */
        NetworkInterface ni = NetworkInterface.getByInetAddress(address);
        if (ni != null) {
            byte[] mac = ni.getHardwareAddress();
            if (mac != null) {
                /*
                 * Extract each array of mac address and convert it to hexa
                 * with the following format 08-00-27-DC-4A-9E.
                 */
                for (int i = 0; i < mac.length; i++) {
                    System.out.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : "");
                    strMac.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "" : ""));
                }
            } else {
                System.out.println("Address doesn't exist or is not accessible.");
            }
        } else {
            System.out.println("Network Interface for the specified address is not found.");
        }
    } catch (Exception e) {

    }
    return strMac.toString();
         }

I have also referred this(Java - Getting MAC address of Linux system) link.

My Ubuntu device uses both LAN & Wifi connection .

Hope my question is clear. Please help ... Thanks

1 Answer 1

2

This is almost a duplicate of Why does java NetworkInterface.getHardwareAddress return empty byte array on Windows? but it's reversed Linux/Windows so I supposed I'll try to answer it.

It looks like you're getting the loopback interface in the address variable, which doesn't register as having a hardware address since it isn't associated with hardware. Try making sure you're getting an InetAddress associated with network hardware. The linked thread has an example of iterating over the list.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.