Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Getting MAC address of Linux system

I'm trying to get the MAC address of a linux system with this code:

try {
  ip = InetAddress.getLocalHost();
  NetworkInterface network = NetworkInterface.getByInetAddress(ip);
  byte[] mac = network.getHardwareAddress();
  // System.out.print("Current MAC address: ");
  for (int i = 0; i < mac.length; i++) {
    is = is + Integer.parseInt(
      String.format("%02X%s", mac[i], (i < mac.length - 1) ? "" : ""),16);
  }
} catch (UnknownHostException e) {
  e.printStackTrace();
} catch (SocketException e) {
  e.printStackTrace();
}

But it just crashes... does anyone know why?

like image 704
y0u Avatar asked Dec 16 '22 12:12

y0u


2 Answers

You might have more than one network interface and I would not count on the interface's name. I suggest you to go over all the interfaces and look for one that has a MAC address. You can use this example as a base line:

try {

        Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
        while(networkInterfaces.hasMoreElements())
        {
            NetworkInterface network = networkInterfaces.nextElement();
            System.out.println("network : " + network);
            byte[] mac = network.getHardwareAddress();
            if(mac == null)
            {
                System.out.println("null mac");             
            }
            else
            {
                System.out.print("MAC address : ");

                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(sb.toString());  
                break;
            }
        }
    } catch (SocketException e){

        e.printStackTrace();

    }
like image 136
Guy Avatar answered Dec 19 '22 03:12

Guy


From your comments, clearly network is null, which means that getByInetAddress() could not find an interface with that IP address (see the JavaDocs: http://download.oracle.com/javase/1.5.0/docs/api/java/net/NetworkInterface.html#getByInetAddress(java.net.InetAddress)).

like image 26
Oliver Charlesworth Avatar answered Dec 19 '22 01:12

Oliver Charlesworth