【问题标题】:Java-Unable to get MAC Address for Ubuntu Device using getHardwareAddress()Java-无法使用 getHardwareAddress() 获取 Ubuntu 设备的 MAC 地址
【发布时间】:2013-07-20 05:43:04
【问题描述】:

我有以下代码为我的 Ubuntu 设备提取 MAC 地址,并且我将 MAC 地址放入数据库。此代码在 windows PC 中运行良好,而在 Ubuntu Device 中同样不起作用。数据库字段为空。我的应用程序是一个 Web 应用程序。我正在获取战争文件并将其放入我的 Ubuntu 设备中的 tomcat 服务器中。

 public static String getMACAddress()
  {
    StringBuffer strMac = new StringBuffer();
    try {

        InetAddress address = InetAddress.getLocalHost();
        // InetAddress address = InetAddress.getByName("192.168.46.53");

        /*
         * Get NetworkInterface for the current host and then read the
         * hardware address.
         */
        NetworkInterface ni = NetworkInterface.getByInetAddress(address);
        if (ni != null) {
            byte[] mac = ni.getHardwareAddress();
            if (mac != null) {
                /*
                 * Extract each array of mac address and convert it to hexa
                 * with the following format 08-00-27-DC-4A-9E.
                 */
                for (int i = 0; i < mac.length; i++) {
                    System.out.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : "");
                    strMac.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "" : ""));
                }
            } else {
                System.out.println("Address doesn't exist or is not accessible.");
            }
        } else {
            System.out.println("Network Interface for the specified address is not found.");
        }
    } catch (Exception e) {

    }
    return strMac.toString();
         }

我也提到了这个(Java - Getting MAC address of Linux system) 链接。

我的 Ubuntu 设备同时使用 LAN 和 Wifi 连接。

希望我的问题很清楚。请帮忙 ... 谢谢

【问题讨论】:

    标签: java jakarta-ee ubuntu tomcat6 mac-address


    【解决方案1】:

    这几乎是Why does java NetworkInterface.getHardwareAddress return empty byte array on Windows? 的复制品,但它颠倒了 Linux/Windows,所以我想我会尝试回答它。

    看起来您在地址变量中获得了环回接口,它没有注册为具有硬件地址,因为它与硬件无关。尝试确保您获得与网络硬件关联的 InetAddress。链接的线程有一个迭代列表的示例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多