Reading The Hardware Address

The below code is working in all system Linux (fedora, centos) and windows except one system (linux). 

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;

public class Test {

    public static String getMacAddress() {

        try {
            InetAddress address = InetAddress.getLocalHost();

            /*
             * Get NetworkInterface for the current host and then read the
             * hardware address.
             */
            System.out.println(address.getCanonicalHostName());
            System.out.println(address.getHostAddress());
            System.out.println(address.isSiteLocalAddress() );
            NetworkInterface ni = NetworkInterface.getByInetAddress(address);
            System.out.println(ni.getDisplayName());
            System.out.println(ni.isUp());
            byte[] mac = ni.getHardwareAddress();

            /*
             * Extract each array of mac address and convert it to hexa with the
             * following format 00-00-27-AA-4A-9E.
             */
            System.out.println(mac.length); // null pointer exception raising ----------------------------
            StringBuilder macaddress= new StringBuilder();
            for (int i = 0; i < mac.length; i++) {
                macaddress.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : "")) ;
            }
            System.out.println("mac "+macaddress);
            return macaddress.toString();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return "";
    }

public static void main(String args[]){
    Test.getMacAddress();
}

Do you have a Java Problem?
Ask It in The Java Forum

Java Books
Java Certification, Programming, JavaBean and Object Oriented Reference Books

Return to : Java Programming Hints and Tips

All the site contents are Copyright © www.erpgreat.com and the content authors. All rights reserved.
All product names are trademarks of their respective companies.
The site www.erpgreat.com is not affiliated with or endorsed by any company listed at this site.
Every effort is made to ensure the content integrity.  Information used on this site is at your own risk.
 The content on this site may not be reproduced or redistributed without the express written permission of
www.erpgreat.com or the content authors.