This example shows how to find the MAC Address or Hardware Address of localhost or local system using Java NetworkInterface class getHardwareAddress() method.
Since JDK 1.6, Java developers are able to access network card detail via NetworkInterface class. In this example, we show you how to get the localhost MAC address in Java.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.UnknownHostException; public class MacAddress { public static void main(String[] args) { InetAddress ip; try { ip = InetAddress.getLocalHost(); System.out.println("Current IP address : " + ip.getHostAddress()); NetworkInterface network = NetworkInterface.getByInetAddress(ip); 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) { e.printStackTrace(); } catch (SocketException e){ e.printStackTrace(); } } } |
Output:
Current IP address : 192.168.1.22
Current MAC address : 00-26-B9-9B-61-BF
Current MAC address : 00-26-B9-9B-61-BF
Note: The NetworkInterfaceNetworkInterface.getHardwareAddress() method is only allowed to access localhost MAC address, not remote host MAC address.