Tuesday, 3 May 2016

How do I get MAC address of a host ?


Use getHardwareAddress() method from java.net.NetworkInterface class.

Code
try {
  InetAddress address = InetAddress.getLocalHost();
  //InetAddress address = InetAddress.getByName("www.google.co.in");
   
  System.out.println("Current IP address: " 
                       address.getHostAddress());

  NetworkInterface network = 
       NetworkInterface.getByInetAddress(address);

  byte[] mac = network.getHardwareAddress();

  System.out.print("Current 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());

} catch (UnknownHostException e) {
  ...
} catch (SocketException e){

  ...
}

No comments:

Post a Comment

Note: only a member of this blog may post a comment.