Ask Your Question
0

What is the method to obtain the MAC Address of a network device using Java?

asked 2023-07-03 22:00:25 +0000

scrum gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-07-03 22:12:01 +0000

lakamha gravatar image

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.

edit flag offensive delete link more

Your Answer

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

Add Answer


Question Tools

Stats

Asked: 2023-07-03 22:00:25 +0000

Seen: 9 times

Last updated: Jul 03 '23