java 在java中使用IP地址查找mac地址
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4436901/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Finding mac Address using IP address in java
提问by sunny
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. If I have the IP address of the other system can I retrieve the MAC address of that system?
我在查找远程主机的 MAC 地址时遇到问题,但我能够找到本地主机的 MAC 地址。如果我有另一个系统的 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 值变为空.... 并且无法获取它.... 但是如果给我的系统的 IP 地址...它获取???
Thanks,
Sunny
谢谢,
阳光
回答by cdhowie
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. MAC addresses of hosts more than one hop away (IP hop, not Ethernet hop) cannot be determined.
您将只能获取本地 LAN 上远程主机的 MAC 地址,即与您的计算机在同一子网中的主机。无法确定超过一跳(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. 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. If you need a technique for a particular OS, you will have to update your question to include that info.
请注意,为本地 LAN 上的主机获取相应的 MAC 地址需要获取 ARP 表或发送和接收原始数据包所需的权限。大多数操作系统允许在没有特殊权限的情况下读取 ARP 表,但您使用的机制会因操作系统而异。如果您需要针对特定操作系统的技术,则必须更新您的问题以包含该信息。