17

イーサネット カードの MAC を取得したい (プロダクト キー用) この種のソリューションを使用して、ここで検索しました。問題は、すべてのネットワーク (イーサネットと Wi-Fi) が切断されたときに、空の MAC アドレスが返されることです。イーサネットが切断されていても、イーサネットのアドレスを取得します。

ありがとう!!

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

3 に答える 3

5

を使用InetAddressすると、IP アドレスのリストを参照するようにバインドされます。インターフェイスがすべて切断されているために何もない場合、そのようなインターフェイスをループすることはできません。

NetworkInterfaceクラスで試してみてください。

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);
    }
  }
}
于 2012-08-27T16:31:49.853 に答える