Reputation: 21329
The following program is meant to print the MAC address of my node. But it prints a blank. I checked it for null but it isn't null. Why would I get a blank MAC address ? What mistake am I committing ?
import java.net.InetAddress;
import java.net.NetworkInterface;
class Tester {
public static void main(String args[]) {
try {
InetAddress address = InetAddress.getByName("localhost");
NetworkInterface ni = NetworkInterface.getByInetAddress(address);
byte mac[] = ni.getHardwareAddress();
if(mac == null) {
System.out.println("Mac address is null");
} else {
System.out.println("Else block!");
String macAdd = new String(mac);
System.out.println(macAdd);
}
} catch(Exception exc) {
exc.printStackTrace();
}
}
}
Note: mac == null
is false.
Upvotes: 1
Views: 2977
Reputation: 6657
You should get localhost by InetAddress.getLocalHost();
instead of InetAddress.getByName("localhost");
.Please refer my below example for the solution of your problem.
import java.net.InetAddress;
import java.net.NetworkInterface;
public class Tester {
public static void main(String args[]) {
try {
InetAddress address = InetAddress.getLocalHost();
NetworkInterface ni = NetworkInterface.getByInetAddress(address);
byte mac[] = ni.getHardwareAddress();
if (mac == null) {
System.out.println("Mac address is null");
} else {
System.out.println("Else block!");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < mac.length; i++) {
sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
}
String macAdd = new String(sb);
System.out.println(macAdd);
}
} catch (Exception exc) {
exc.printStackTrace();
}
}
}
Output
Else block!
44-87-FC-F1-D4-77
NOTE :-
Remember that it is important to convert the mac address recieved into readable hexadecimal format, so I have written the below code block. If you dont do that then you will received garbage text as D‡üñÔw
.
StringBuilder sb = new StringBuilder();
for (int i = 0; i < mac.length; i++) {
sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
}
String macAdd = new String(sb);
Upvotes: 1
Reputation: 56123
The MAC address is an array of bytes, the first of which may be zero.
To print it you need to convert it to a printable, alphanumeric (e.g. hexadecimal) format, for example using String.format as shown in Bhavik Ambani's answer.
Upvotes: 0
Reputation: 32296
According to this discussion, "Well, the interface that reacts to "localhost" is usually the loopback device, which doesn't have a MAC address, so that might be your reason."
Upvotes: 4
Reputation: 534
If you check the JavaDocs for Java 7, you will notice there's the getLocalhost()
which is what you probably want.
Upvotes: 0
Reputation: 533740
I have never seen a localhost
loop back interface with a MAC address. I suspect it's not very useful.
System.out.println(Arrays.toString(mac));
prints
[]
which is not surprising as its only a virtual software device.
Upvotes: 2