当前位置: 动力学知识库 > 问答 > 编程问答 >

networking - Java Get mac address of disconnected card

问题描述:

I want to get the MAC of the ethernet card (for product key)

I tried using this kind of solution and searched here, the problem is that when all the networking is disconnected (ethernet and wifi) it returns empty MAC adress.

I rather get the adress of the ethernet even if it's disconnected.

Thanks!!

 public static void main(String[] args)

{

InetAddress ip;

try {

ip = InetAddress.getLocalHost();

System.out.println("The mac Address of this machine is :" + ip.getHostAddress());

NetworkInterface network = NetworkInterface.getByInetAddress(ip);

byte[] mac = network.getHardwareAddress();

System.out.print("The mac address is : ");

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

}

catch (UnknownHostException e) {

e.printStackTrace();

}

catch (SocketException e) {

e.printStackTrace();

}

}

}

网友答案:

Using InetAddress binds you to look in a list of IP addresses. If you have none because the interfaces are all disconnected, then you can't loop over such interfaces.

You should try with NetworkInterface class.

public class MacAddressTest
{
  public static void main(String[] args) throws Exception
  {
    Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();

    while (interfaces.hasMoreElements())
    {
      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)));
        }
      }

      System.out.println(lStringBuffer);
    }
  }
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: