Get MAC Address using Java

MAC Address can be obtained using the NetworkInterface class. This class represents a Network Interface made up of a name, and a list of IP addresses assigned to this interface. It is used to identify the local interface on which a multicast group is joined. A network interface is the point of interconnection between a computer and a private or public network.

basic mac address format

code to get the MAC address

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){
 
	try {
 
		InetAddress localhost = InetAddress.getLocalHost();

		System.out.println("IP address : " + localhost.getHostAddress());
 
		NetworkInterface network = NetworkInterface.getByInetAddress(localhost);
 
		byte[] mac = network.getHardwareAddress();
 
		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("MAC address : "+sb.toString());
 
	} catch (UnknownHostException e) {
 
		e.printStackTrace();
 
	} catch (SocketException e){
 
		e.printStackTrace();
	}
   } 
}

output:-

IP address : 192.168.1.1
MAC address : 24-35-10-Z7-6H-17

Leave a Comment