簡體   English   中英

為什么我得到一個空白的MAC地址?

[英]Why do I get a blank MAC address?

以下程序用於打印我的節點的MAC地址。 但它打印空白。 我檢查它是否為null,但不為null。 為什么我會得到一個空白的MAC地址? 我犯了什么錯誤?

import java.net.InetAddress;
import java.net.NetworkInterface;

class Tester {
public static void main(String args[]) {
    try {
      InetAddress address = InetAddress.getByName("localhost");
      NetworkInterface ni = NetworkInterface.getByInetAddress(address);
      byte mac[] = ni.getHardwareAddress();
      if(mac == null) {
        System.out.println("Mac address is null");
      } else {
        System.out.println("Else block!");
        String macAdd = new String(mac);
        System.out.println(macAdd);
      }

    } catch(Exception exc) {
       exc.printStackTrace();
    }
}
}

注意: mac == null為false。

根據這次討論“好吧,對“ localhost”做出反應的接口通常是回送設備,它沒有MAC地址,因此這可能是您的原因。

我從未見過具有MAC地址的localhost環回接口。 我懷疑這不是很有用。

System.out.println(Arrays.toString(mac));

版畫

[]

這並不奇怪,因為它只是一個虛擬軟件設備。

您應該通過InetAddress.getLocalHost();獲得本地主機InetAddress.getLocalHost(); 而不是InetAddress.getByName("localhost"); 請參考以下示例以解決您的問題。

import java.net.InetAddress;
import java.net.NetworkInterface;

public class Tester {
    public static void main(String args[]) {
        try {
            InetAddress address = InetAddress.getLocalHost();
            NetworkInterface ni = NetworkInterface.getByInetAddress(address);
            byte mac[] = ni.getHardwareAddress();
            if (mac == null) {
                System.out.println("Mac address is null");
            } else {
                System.out.println("Else block!");
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < mac.length; i++) {
                    sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));        
                }
                String macAdd = new String(sb);
                System.out.println(macAdd);
            }

        } catch (Exception exc) {
            exc.printStackTrace();
        }
    }
}

輸出量

Else block!
44-87-FC-F1-D4-77

注意 :-

請記住,將接收到的mac地址轉換為可讀的十六進制格式很重要,因此我編寫了以下代碼塊。 如果您不這樣做,那么您將收到垃圾D‡üñÔw

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < mac.length; i++) {
                sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));        
            }
            String macAdd = new String(sb);

如果您檢查Java 7的JavaDocs ,您會發現可能是您想要的getLocalhost()

MAC地址是一個字節數組,其第一個可以為零。

要打印它,您需要將其轉換為可打印的字母數字(例如十六進制)格式,例如使用Bhavik Ambani的答案中所示的String.format。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM