To obtain the MAC address of a network device using Java, you can use the following code:
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 ipAddress = InetAddress.getLocalHost();
NetworkInterface networkInterface = NetworkInterface.getByInetAddress(ipAddress);
byte[] macAddressBytes = networkInterface.getHardwareAddress();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < macAddressBytes.length; i++) {
sb.append(String.format("%02X%s", macAddressBytes[i], (i < macAddressBytes.length - 1) ? "-" : ""));
}
String macAddress = sb.toString();
System.out.println(macAddress);
} catch (UnknownHostException | SocketException e) {
e.printStackTrace();
}
}
}
This code uses the InetAddress
class to get the local IP address and the NetworkInterface
class to obtain the MAC address of the network device associated with that IP address. The MAC address is obtained as a byte array, which is then converted to a string in the format XX-XX-XX-XX-XX-XX
.
Asked: 2023-07-03 22:00:25 +0000
Seen: 9 times
Last updated: Jul 03 '23