2010-12-14 150 views
1
public static void main(String[] args) { 
    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) ? "-" : ""); 
       } 
      } 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."); 
     } 

我在查找遠程主機的MAC地址時遇到問題,但我能找到本地主機的MAC地址。如果我有其他系統的IP地址,我可以檢索該系統的MAC地址嗎?在java中使用IP地址查找mac地址

InetAddress address = InetAddress.getByName(「192.168.46.53」);

如果我在我的工作組中指定了一個系統的IP地址...... ni的值爲空....並且不能獲取它......但是如果給我的系統的ip地址......它取???

感謝,
陽光

+4

爲什麼你認爲你應該能夠獲得遠程主機的Mac地址(不在你本地的子網上)。這不是IP協議要求(或傳達)的東西。你可以得到的最好的是你的網關的Mac地址。 – 2010-12-14 07:45:51

+0

netAddress address = InetAddress.getByName(「192.168.46.53」); 如果我指定在我的工作組中的系統的IP地址... ni值得到空....並且不能獲取它....但如果給我的我的系統的IP地址......它提取? ?? – sunny 2010-12-14 09:39:31

回答

7

你將只能在本地局域網上獲取遠程主機的MAC地址,也就是主機是在同一子網與您的計算機。不能確定超過一跳的主機的MAC地址(IP跳,而不是以太網跳)。

注意,爲本地LAN上的主機獲取相應的MAC地址需要獲取ARP表或者發送和接收原始數據包所必需的權限。大多數操作系統都允許讀取ARP表,而無需特殊權限,但您使用的機制將根據操作系統而改變。如果您需要針對特定​​操作系統的技術,則必須更新您的問題以包含該信息。