简体   繁体   English

如何在Java中获取以太网和wifi卡的Mac? (仅2张卡)

[英]how to get mac of ethernet and wifi card in java? (only 2 card)

I want to get mac(for license product), but I received too many result (sorry if my English is not good): 我想获得mac(用于许可产品),但是收到了太多结果(对不起,如果我的英语不好):

    public void testGetMac() throws SocketException {
    Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();

    int i = 0;
    while (interfaces.hasMoreElements() && i < 3)
    {
        NetworkInterface nif = interfaces.nextElement();
        byte[] lBytes = nif.getHardwareAddress();
        StringBuffer lStringBuffer = new StringBuffer();

        if (lBytes != null)
        {
            for (byte b : lBytes)
            {
                lStringBuffer.append(String.format("%1$02X ", new Byte(b)));
            }
            i ++;
        }

        System.out.println(lStringBuffer);

    }
}

This is how I was reading MAC in my app. 这就是我在应用程序中读取MAC的方式。 Hope this helps... 希望这可以帮助...

InetAddress ip = InetAddress.getLocalHost();

        Enumeration e = NetworkInterface.getNetworkInterfaces();

        while (e.hasMoreElements()) {

            NetworkInterface n = (NetworkInterface) e.nextElement();
            Enumeration ee = n.getInetAddresses();
            while (ee.hasMoreElements()) {
                InetAddress i = (InetAddress) ee.nextElement();
                if (!i.isLoopbackAddress() && !i.isLinkLocalAddress()
                        && i.isSiteLocalAddress()) {
                    ip = i;
                }
            }
        }

        NetworkInterface network = NetworkInterface.getByInetAddress(ip);
        if(network == null){
            String message = "Check your internet connection!";
            JOptionPane.showMessageDialog(null, message,"Error", JOptionPane.ERROR_MESSAGE);
            return false;
        }
        byte[] address = network.getHardwareAddress();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM