package com.fs.common;

import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

public class DeviceUtils {
    public static String getMacAddress() {
        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            StringBuilder sb = new StringBuilder();
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = networkInterfaces.nextElement();
                byte[] mac = networkInterface.getHardwareAddress();
                if (mac != null) {

                    for (int i = 0; i < mac.length; i++) {
                        sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
                    }
                    return sb.toString(); //返回第一个不为空的mac地址
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return null;
    }
     public static void main(String[] args) {
        String macAddress = getMacAddress();
        if (macAddress != null) {
            System.out.println("MAC Address: " + macAddress);
        } else {
            System.out.println("Could not retrieve MAC Address.");
        }
    }
}
