Java Top

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE

1. Introduction

In this tutorial, we'll use Java to get the MAC addresses of a local machine.

A MAC address is the unique identifier for a physical network interface card.

We'll cover MAC addresses only, but for a more general overview of network interfaces, refer to Working with Network Interfaces in Java.

2. Examples

In our examples below, we'll make use of the java.net.NetworkInterface and java.net.InetAddress APIs.

2.1. Machine Localhost

First, let's get the MAC address for our machine's localhost:

InetAddress localHost = InetAddress.getLocalHost();
NetworkInterface ni = NetworkInterface.getByInetAddress(localHost);
byte[] hardwareAddress = ni.getHardwareAddress();

As NetworkInterface#getHardwareAddress returns an array of bytes, we can format the result:

String[] hexadecimal = new String[hardwareAddress.length];
for (int i = 0; i < hardwareAddress.length; i++) {
    hexadecimal[i] = String.format("%02X", hardwareAddress[i]);
}
String macAddress = String.join("-", hexadecimal);

Notice how we format each byte in the array to a hexadecimal number using String#format.

After that, we can join all the formatted elements with a “-” (dash).

2.2. Local IP

Secondly, let's get the MAC address for a given local IP address:

InetAddress localIP = InetAddress.getByName("192.168.1.108");
NetworkInterface ni = NetworkInterface.getByInetAddress(localIP);
byte[] macAddress = ni.getHardwareAddress();

Again, notice how we get an array of bytes for the MAC address.

2.3. All Network Interfaces

Finally, let's get the MAC addresses for all the network interfaces on our machine:

Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
    NetworkInterface ni = networkInterfaces.nextElement();
    byte[] hardwareAddress = ni.getHardwareAddress();
    if (hardwareAddress != null) {
        String[] hexadecimalFormat = new String[hardwareAddress.length];
        for (int i = 0; i < hardwareAddress.length; i++) {
            hexadecimalFormat[i] = String.format("%02X", hardwareAddress[i]);
        }
        System.out.println(String.join("-", hexadecimalFormat));
    }
}

As getNetworkInterfaces returns both physical and virtual interfaces, we need to filter out the virtual ones.

We can do this for example, by doing a null check on getHardwareAddress.

3. Conclusion

In this quick tutorial, we explored different ways of getting MAC addresses for a local machine.

As usual, all the source code with the examples in this tutorial can be found over on GitHub.

Java bottom

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE
guest
0 Comments
Inline Feedbacks
View all comments