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.
Example : Get MAC Address via NetworkInterface.getByInetAddress()
Consider the following method which returns the MAC address of the computer:
Example : Get MAC Address via NetworkInterface.getByInetAddress()
Consider the following method which returns the MAC address of the computer:
public static String getMacAddress(){
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();
}
}
Excellent
ReplyDeleteThis comment has been removed by the author.
ReplyDelete