在java中使用IP地址查找mac地址

时间:2010-12-14 07:40:39

标签: java sockets url

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地址吗?

InetAddress address = InetAddress.getByName(“192.168.46.53”);

如果我在我的工作组中指定系统的IP地址... ni值变为空....并且无法获取它....但是如果给我的系统的IP地址...它取出???

谢谢,
晴天

1 个答案:

答案 0 :(得分:7)

您只能获取本地LAN上远程主机的MAC地址,即与您的计算机位于同一子网中的主机。主机的MAC地址超过一跳(IP跳,而不是以太网跳)无法确定。

请注意,为本地LAN上的主机获取相应的MAC地址需要获取ARP表所需的权限,或者发送和接收原始数据包所需的权限。大多数操作系统允许在没有特殊权限的情况下读取ARP表,但您使用的机制将根据操作系统而改变。如果您需要针对特定​​操作系统的技术,则必须更新您的问题以包含该信息。

相关问题