简体   繁体   English

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

[英]Finding mac Address using IP address in java

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.");
        }

I'm having a problem finding the MAC address of a remote host, but I am able to find the MAC address of my local host. 我在查找远程主机的MAC地址时遇到问题,但是我能够找到本地主机的MAC地址。 If I have the IP address of the other system can I retrieve the MAC address of that system? 如果我拥有其他系统的IP地址,可以检索该系统的MAC地址吗?

InetAddress address = InetAddress.getByName("192.168.46.53"); InetAddress地址= InetAddress.getByName(“ 192.168.46.53”);

if i specify the ip address of a system in my workgroup... ni values gets null.... and not able to fetch it.... but if give my ip address of my system...it fetches??? 如果我在工作组中指定系统的IP地址... ni值将为null ....并且无法获取....但是如果提供我系统的IP地址...则会获取???

Thanks, 谢谢,
Sunny 阳光明媚

You will only be able to fetch the MAC address of remote hosts on your local LAN, that is, hosts that are in the same subnet as your computer. 您将只能在本地LAN上获取远程主机的MAC地址,即与计算机位于同一子网中的主机。 MAC addresses of hosts more than one hop away (IP hop, not Ethernet hop) cannot be determined. 无法确定距离多跳(IP跳,而不是以太网跳)的主机的MAC地址。

And note that fetching the corresponding MAC address for hosts on your local LAN requires the permissions necessary to fetch either the ARP table, or those necessary to send and receive raw packets. 请注意,为本地LAN上的主机获取对应的MAC地址需要获取ARP表或发送和接收原始数据包所必需的权限。 Most OSes allow reading of the ARP table without special permissions, but the mechanism you use to do so will change depending on the OS. 大多数操作系统允许在没有特殊权限的情况下读取ARP表,但是您使用的机制会因操作系统而异。 If you need a technique for a particular OS, you will have to update your question to include that info. 如果您需要特定操作系统的技术,则必须更新您的问题以包含该信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM