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表,而无需特殊权限,但您使用的机制将根据操作系统而改变。如果您需要针对特定​​操作系统的技术,则必须更新您的问题以包含该信息。