Monday, June 15, 2009

Finding MAC Address using Java

MAC Address stands for Media Access Control Address. It is a unique identifier to most network interface cards (LAN Card) by the manufacturer for identification. The MAC which is also known as a physical address or adapter address usually encodes the registered identification number of the manufacturer.


You can always find the MAC address of the computer by going to command prompt and type: ipconfig /all. The physical address of the machine is printed like the below format: 08-00-27-DC-4A-9E.


Here I am going to put the code to find out MAC address of a machine using JAVA.
We will do it using getHardwareAddress() method of NetworkInterface class of java.net package. The method has been introduced in the JDK 1.6. So the below program is compatible with JDK 1.6.

import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;

public class MacAddress {

public static void main(String[] args) {
try {

InetAddress address = InetAddress.getLocalHost();
System.out.println("Address "+address);
/*
* Get NetworkInterface for the current host and then read the
* hardware address.
*/
NetworkInterface ni = NetworkInterface.getByInetAddress(address);
System.out.println("NI = "+ni);
byte[] mac = ni.getHardwareAddress();


/*
* Extract each array of mac address and convert it to hexa with the
* following format 08-00-27-DC-4A-9E.
*/

System.out.println("MAC Address is ");
for (int i = 0; i < mac.length; i++) {
System.out.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : "");
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (SocketException e) {
e.printStackTrace();
}
}
}

1 comment:

Imdad said...

This code is printing the MAC Address of localhost but doesn't print the MAC address of other computers on network. Could u plz help in this regaard.

Total Pageviews