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
.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2023-07-03 22:00:25 +0000
Seen: 13 times
Last updated: Jul 03 '23
How can set the Project Title in the Doxygen Configuration File?
How can I convert Double to Long in Java?
Can I add a default Parameter for a Method in Java like int calculate(int x, int y=2)?
How can the rejection of the class text_plain from JavaMail API due to a VerifyError be confirmed?
Is it feasible to utilize a Toggle Button to switch among multiple classes exceeding 2?
How can I set up Environment variables on my M1 MacBook and resolve the ZSH permission denied error?
What is the process for generating a dynamic subdomain/URL using vue.js?