9

I am using this code to find the MAC address of a machine. This code prints directly the MAC address, but I want to return it as a string. I am completely confused.

please help.

try {

    InetAddress add = InetAddress.getByName("10.123.96.102");
    NetworkInterface ni1 = NetworkInterface.getByInetAddress(add);
    if (ni1 != null) {
        byte[] mac1 = ni1.getHardwareAddress();
        if (mac1 != null) {
            for (int k = 0; k < mac1.length; k++) {
                System.out.format("%02X%s", mac1[k], (k < mac1.length - 1) ? "-" : "");
            }
        } else {
            System.out.println("Address doesn't exist ");
        }
        System.out.println();
    } else {
        System.out.println("address is not found.");
    }
} catch (UnknownHostException e) {
    e.printStackTrace();
} catch (SocketException e) {
    e.printStackTrace();
}
bluish
  • 26,356
  • 27
  • 122
  • 180
rgksugan
  • 3,521
  • 12
  • 45
  • 53
  • 1
    If you need to return a string formatted the same way, use a StringBuilder, and append to it in a loop parts formatted with String.format(..). – Eyal Schneider May 09 '10 at 11:09
  • See http://stackoverflow.com/questions/311165/how-do-you-convert-byte-array-to-hexadecimal-string-and-vice-versa-in-c/632920#632920 – Zaki May 09 '10 at 11:11

11 Answers11

25

There is no standard text representation for Mac addresses. You just need to convert it to hex and separate the bytes for readability. Here is the function I use in the format of ifconfig on Unix,

public static String getMacAddress(String ipAddr)
        throws UnknownHostException, SocketException {
    InetAddress addr = InetAddress.getByName(ipAddr);
    NetworkInterface ni = NetworkInterface.getByInetAddress(addr);
    if (ni == null)
        return null;

    byte[] mac = ni.getHardwareAddress();
    if (mac == null)
        return null;

    StringBuilder sb = new StringBuilder(18);
    for (byte b : mac) {
        if (sb.length() > 0)
            sb.append(':');
        sb.append(String.format("%02x", b));
    }
    return sb.toString();
}

You just need to change the ':' to '-'.

ZZ Coder
  • 74,484
  • 29
  • 137
  • 169
  • This looks nice to me. It is possible to avoid the String.format() too if performance is a concern as it is a notoriously slow function. – Chris May 20 '11 at 17:46
  • It gives me NullPointerException at line `NetworkInterface ni = NetworkInterface.getByInetAddress(addr);` but my InetAddress object contains valid IPAddress...any help is appreciated.... – Durrat Mar 22 '13 at 08:56
  • @Chris it's unlikely a few calls to String.format will be the bottleneck in an application – Heuriskos Mar 26 '20 at 13:42
4

By this you can easily formate Mac Address String.

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

public class App{

   public static void main(String[] args){

    InetAddress ip;
    try {

        ip = InetAddress.getLocalHost();
        System.out.println("Current IP address : " + ip.getHostAddress());

        NetworkInterface network = NetworkInterface.getByInetAddress(ip);

        byte[] mac = network.getHardwareAddress();

        System.out.print("Current MAC address : ");

        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(sb.toString());

    } catch (UnknownHostException e) {

        e.printStackTrace();

    } catch (SocketException e){

        e.printStackTrace();

    }

   }

}

copy from here : http://www.mkyong.com/java/how-to-get-mac-address-in-java/comment-page-1/#comment-139182

Az MaYo
  • 41
  • 1
3

Perhaps you could use Hex.encodeHex(bytes) from commons-codec.

Here are other ways to do this, without 3rd party libraries.

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
1

It should be something like

StringBuilder sb = new StringBuilder();
for (int i = 0; i < mac.length(); i++) {
    b.append(String.format("%02X%s", mac[i], (i < mac.length() - 1) ? "-" : "");

String s = sb.toString();
Abdelsalam Shahlol
  • 1,621
  • 1
  • 20
  • 31
dude
  • 4,532
  • 8
  • 33
  • 51
0

I know this is a Java related question, but for Scala users who ended up here like I did, this is a way to do it in Scala:

bytes.map("%02X" format _).mkString (":")
Jeroen Kransen
  • 1,379
  • 3
  • 19
  • 45
0
  private static final byte[] NULL_MAC = new byte[] {0, 0, 0, 0, 0, 0};

  public static String getMacString(byte[] macAddress) {
    StringBuilder retval = new StringBuilder(17);
    if (macAddress == null) {
      macAddress = NULL_MAC;
    }
    boolean isFirst = true;
    for (byte b : macAddress) {
      if (!isFirst) {
        retval.append(":");
      } else {
        isFirst = false;
      }
      retval.append(String.format("%02x", b & 0xff));
    }
    return retval.toString();
  }
TJR
  • 3,617
  • 8
  • 38
  • 41
0

For something lightweight and fast, try the following. 3rd party external dependencies are minimal and just uses some "old school" bit math.

public static String buildMACAddressString(byte[] macaddress) {
    char[] buffer = new char[macaddress.length*3];
    char[] inttohex= {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
    int destIndex=0;
    byte byteValue;
    for (int i = 0; i < macaddress.length; i++) {
        // pull current byte value
        byteValue = (byte) (macaddress[i] & 0xff);
        // convert high nibble to hex char and store into char array..
        buffer[destIndex++]=inttohex[(byteValue&0xf0)>>4];
        // Convert low nibble to hex char and store into char array..
        buffer[destIndex++]=inttohex[byteValue&0xf];
        // Inject spacer
        if (i < macaddress.length-1)
            buffer[destIndex++]=':';
    }
    return String.valueOf(buffer,0,destIndex);
}
Pang
  • 9,564
  • 146
  • 81
  • 122
Jim Row
  • 41
  • 4
0
String s="";
for (int i = 0; i < mac.length; i++) { 
  s += String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : "");
}
Andreas Dolk
  • 113,398
  • 19
  • 180
  • 268
  • 2
    Concatenating strings with += is extremely inefficient (use a StringBuilder instead as in the other answers). Additionally, it appears that you have bundled up too much code onto a single line which neither helps nor hinders performance but does produce unreadable code when scaled up to many thousands of lines. – Chris May 20 '11 at 17:43
0

There is a new way, but it seems it requires Java 17.

You can use the java.util.HexFormat class, specifically define a format (e.g. ofDelimiter(":"), there are many more formatting possibilities), and then use the formatter (e.g. hexFormat.formatHex(ni.getHardwareAddress())).

    private List<String> getHardwareAddresses(List<byte[]> ipAddresses) {
        HexFormat hexFormat = HexFormat.ofDelimiter(":");
        List<String> hardwareAddresses = new ArrayList<>();
        try {
            for (byte[] ipAddress : ipAddresses) {
                NetworkInterface ni = NetworkInterface.getByInetAddress(InetAddress.getByAddress(ipAddress));
                if (ni.getHardwareAddress() != null) {
                    hardwareAddresses.add(hexFormat.formatHex(ni.getHardwareAddress()));
                }
            }
        } catch (SocketException | UnknownHostException e) {
            e.printStackTrace();
        }
        return hardwareAddresses;
    }

In the example above I have a list of IP addresses as List<byte[]> and use them to get the MAC addresses of those devices if available (if (ni.getHardwareAddress() != null) {...}).

Voronin
  • 159
  • 1
  • 7
0

Java 17+:

private static String formatMacHex(byte[] mac) {
    return HexFormat.ofDelimiter("-").formatHex(mac);
}
ZhekaKozlov
  • 36,558
  • 20
  • 126
  • 155
0

A kotlin version:

private fun convertToMacAddress(macByteArray: ByteArray): String {
    return macByteArray.joinToString(":") { String.format("%02x", it) }
}
William Hu
  • 15,423
  • 11
  • 100
  • 121