如何在java中获取以太网和wifi卡的mac? (只有2张卡)

时间:2014-06-02 09:57:47

标签: java

我想获得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);

    }
}

1 个答案:

答案 0 :(得分:0)

这就是我在我的应用中阅读MAC的方式。希望这会有所帮助...

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();