首页javaip_addressJava Network - 如何格式化MAC地址字节数组为String

Java Network - 如何格式化MAC地址字节数组为String

我们想知道如何格式化MAC地址字节数组为String。
import java.net.InetAddress;
import java.net.NetworkInterface;

public class Main {

  public static void main(String[] args) throws Exception {
    InetAddress 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());
  }
}