Java Network Programming – Working With MAC Addresses

Share

Getting a MAC address
A Media Access Control (MAC) address is used to identify an NIC. MAC addresses
are usually assigned by the manufacturer of an NIC and are a part of its hardware.
Each NIC on a node must have a unique MAC address. Theoretically, all NICs,
regardless of their location, will have a unique MAC address. A MAC address
consists of 48 bits that are usually written in groups of six pairs of hexadecimal
digits. These groups are separated by either a dash or a colon.
Getting a specific MAC address

Normally, MAC addresses are not needed by the average Java programmer.
However, they can be retrieved whenever needed. The following method returns
a string containing the IP address and its MAC address for a NetworkInterface
instance. The getHardwareAddress method returns an array of bytes holding the
number. This array is then displayed as a MAC address. Most of this code-segment
logic is devoted to formatting the output, where the tertiary operator determines
whether a dash should be displayed:

        public String getMACIdentifier(NetworkInterface network) {
            StringBuilder identifier = new StringBuilder();
            try {
                byte[] macBuffer = network.getHardwareAddress();
                if (macBuffer != null) {
                    for (int i = 0; i < macBuffer.length; i++) {
                        identifier.append(
                                String.format("%02X%s",macBuffer[i],
                                        (i < macBuffer.length - 1) ? "-" : ""));
                    }
                } else {
                    return "---";
                }
            } catch (SocketException ex) {
                ex.printStackTrace();
            }
            return identifier.toString();
        }

The method is demonstrated in the following example where we use the localhost:

        InetAddress address = InetAddress.getLocalHost();
        System.out.println("IP address: " + address.getHostAddress());
        NetworkInterface network =
                NetworkInterface.getByInetAddress(address);
        System.out.println("MAC address: " +
                getMACIdentifier(network));
                

The output will vary depending on the computer used. One possible output is
as follows:

IP address: 192.168.1.5
MAC address: EC-0E-C4-37-BB-72

Getting multiple MAC addresses
Not all network interfaces will have MAC addresses. This is demonstrated here,
where an enumeration is created using the getNetworkInterfaces method, and
then each network interface is displayed:

        Enumeration<NetworkInterface> interfaceEnum =
                NetworkInterface.getNetworkInterfaces();
        System.out.println("Name MAC Address");
        for (NetworkInterface element :
                Collections.list(interfaceEnum)) {
            System.out.printf("%-6s %s\n",
                    element.getName(), getMACIdentifier(element));
        
One possible output is as follows. The output is truncated to save space:
Name MAC Address
lo ---
eth0 ---
eth1 8C-DC-D4-86-B1-05
wlan0 EC-0E-C4-37-BB-72
wlan1 EC-0E-C4-37-BB-72
net0 ---
net1 00-00-00-00-00-00-00-E0
net2 00-00-00-00-00-00-00-E0

Alternatively, we can use the following Java implementation. It converts the
enumeration into a stream and then processes each element in the stream:

        interfaceEnum = NetworkInterface.getNetworkInterfaces();
        Collections
                .list(interfaceEnum)
                .stream()
                .forEach((inetAddress) -> {
                    System.out.printf("%-6s %s\n",
                            inetAddress.getName(),
                            getMACIdentifier(inetAddress));
                });

The power of streams comes when we need to perform additional processing, such as
filtering out certain interfaces, or converting the interface into a different data type.

You may also like...