Previously for obtaining a MAC address we need to use a native code as a solution. In JDK 1.6 a new method is added in the java.net.NetworkInterface
class, this method is getHardwareAddress()
.
package org.kodejava.net;
import java.net.InetAddress;
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();
InetAddress address = InetAddress.getByName("192.168.0.105");
/*
* Get NetworkInterface for the current host and then read
* the hardware address.
*/
NetworkInterface ni = NetworkInterface.getByInetAddress(address);
if (ni != null) {
byte[] mac = ni.getHardwareAddress();
if (mac != null) {
/*
* Extract each array of mac address and convert it
* to hexadecimal with the following format
* 08-00-27-DC-4A-9E.
*/
for (int i = 0; i < mac.length; i++) {
System.out.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : "");
}
} else {
System.out.println("Address doesn't exist or is not accessible.");
}
} else {
System.out.println("Network Interface for the specified address is not found.");
}
} catch (UnknownHostException | SocketException e) {
e.printStackTrace();
}
}
}
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024
I’m skeptic to this code example. Granted, this is absolutely something that runs and will get you the mac address on your local interface if that is the IP address you supply. However obtaining “a mac address” generally on your local subnet you would use an ARP request and I was just researching how to to that for a java app and as I understand you can’t do it natively in Java, please enlighten me if I’m wrong.
Did you mean to write the post “How do I get MY mac address?” or am I missing something?
Only for local address right?
The third parameter on the format method is not documented anywhere. Where can I find documentation?
Also, can you explain how that ternary function works exactly? Thanks!
Hi Trent,
The parameter definition of the method is
System.out.format(String format, Object... args)
it means that it takes a string as the first parameter and a variable number of objects as the following parameters. The...
symbol also called a varargs, it allows you to pass an arbitrary number of values to a method.