In this example, let’s see how to get the localhost MAC address in Java.
Source Code
package com.beginner.examples;
import java.net.InetAddress;
import java.net.NetworkInterface;
public class GetMACexample {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
InetAddress ip = InetAddress.getLocalHost();
System.out.println("ip:" + 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++) {
int tmpe = mac[i] & 0xff;
String s = Integer.toHexString(tmpe);
if (i == mac.length - 1) {
sb.append(s);
} else {
sb.append(s + "-");
}
}
System.out.println(sb.toString());
} catch (Exception e) {
}
}
}
Output:
ip:192.168.0.132
Current MAC address : 40-a5-ef-45-f1-97