1. 程式人生 > 實用技巧 >JAVA獲取指定的型別的本機MAC地址

JAVA獲取指定的型別的本機MAC地址

前面我們運維小夥在部署的時候,發現在真實伺服器獲取不到mac地址或者獲取不到指定型別的mac地址,寫程式記錄如下

import com.google.common.base.Strings;

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

public class MacHelper {


    private static MacHelper instance;

    public static MacHelper getInstance() {

        if (instance == null) {
            synchronized (MacHelper.class) {
                instance = new MacHelper();
            }
        }

        return instance;
    }

    /**
     * 獲取本地IP
     *
     * @return String
     */
    public String getFirstLocalMac() {
        String startName = "eth", symbol = "";
        return getFirstLocalMac(startName, symbol);
    }

    /**
     * 獲取本地IP
     *
     * @return String
     */
    public String getFirstLocalMac(String startName, String symbol) {

        try {

            Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();

            while (enumeration.hasMoreElements()) {

                NetworkInterface networkInterface = enumeration.nextElement();

                if (networkInterface == null) {
                    continue;
                }


                if (!(networkInterface.getName().equals(startName) ||
                        networkInterface.getName().startsWith(startName))) {
                    continue;
                }


                //獲取網絡卡,獲取地址
                byte[] mac = networkInterface.getHardwareAddress();

                if (mac == null || mac.length <= 0) {
                    continue;
                }


                StringBuilder sb = new StringBuilder();

                int i = 0;

                for (byte b : mac) {
                    //位元組轉換為整數
                    int temp = b & 0xff;
                    String str = Integer.toHexString(temp);

                    if (!Strings.isNullOrEmpty(symbol) && i == 0) {
                        sb.append(symbol);
                    }

                    if (str.length() == 1) {
                        sb.append("0").append(str);
                    } else {
                        sb.append(str);
                    }

                    i++;
                }

                return sb.toString().toLowerCase();

            }


        } catch (Exception e) {
            e.printStackTrace();
        }

        return "";
    }
}