Friday, December 8, 2017

JAVA - How to get device MAC address

For getting MAC address of the device use this code:
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.net.SocketException;
...
try {
  InetAddress ia = InetAddress.getLocalHost();

  NetworkInterface ni = NetworkInterface.getByInetAddress( ia );

  /* -- write results */

  System.out.println( ni.getName() );
  System.out.println( ni.getDisplayName() );

  byte[] mac = ni.getHardwareAddress();

  for ( int i = 0; i < mac.length; i++ )
    System.out.format( "%02X%s",  mac[i], ( i < mac.length - 1 ) ? "-" : "" );

  } 
  catch ( UnknownHostException ex ) {} 
  catch ( SocketException ex ) {}
...
Output:
Realtek PCIe GBE Family Controller - Packet Scheduler Miniport
eth2
70-71-BC-54-E7-8B

No comments:

Post a Comment