I want get machines\' MAC address..but below written code only display the MAC address when Internet is connected to my machine other it will return null... I am using windows 7
Seems like you are trying to get the MAC address by IP address. An IP address exists only when you are connected successfully to the Internet. Otherwise, it will be null
, as you state.
Try this: NetworkInterface.getHardwareAddress().
If you want the MAC address of all network interfaces on your computer, try this: NetworkInterface.getNetworkInterfaces().
EDIT: After reviewing the code again, I realize that you have my suggestion implemented. However, you are only trying to obtain the MAC address if you have a valid IP. You will not have a valid IP if are not connected to the Internet.
public static void main(String[] args)
{
NetworkInterface network;
byte[] mac = network.getHardwareAddress();
System.out.print("The mac address is : ");
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());
}