Convert MAC address byte array to String

Total Views : 55
Zoom In Zoom Out Read Later Print

This code will help you to know how you can convert or format MAC address byte array into string.

MacByteToString.java

package com.prodevsblog.how_to.network.ip;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;

public class MacByteToString {

    public static void main(String[] args){
        try {
            InetAddress ip = InetAddress.getLocalHost();

            // Private Ip Address
            System.out.println("IP address : " + ip.getHostAddress());

            NetworkInterface network = NetworkInterface.getByInetAddress(ip);
            byte[] mac = network.getHardwareAddress();

            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < mac.length; i++) {
                sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
            }
            System.out.println("Mac Address : " + sb.toString());

        } catch (UnknownHostException | SocketException uhse) {
            uhse.printStackTrace();
        }
    }
}

Output of the code.

Output:

IP address : 192.168.43.102
Mac Address : 3C-A9-F4-35-86-CC

Process finished with exit code 0

See More

Latest Photos