I need to get the MAC ID of a host in my network. For that, if I ping to that IP and query the ARP cache arp -a
, I am able to get the MAC ID. I just wonder if I can get any API to query the ARP and get the MAC id.
Also, if there is a better method to get the MAC ID from IP address, please suggest.
P.S: I am working in JAVA.
Thanks.
There is a much simpler way:
private static final String ARP_GET_IP_HW = "arp -a";
public String getARPTable(String cmd) throws IOException {
Scanner s = new Scanner(Runtime.getRuntime().exec(cmd).getInputStream()).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
System.out.println(getARPTable(ARP_GET_IP_HW ));
And you get the eintire ARP Table with IP and HW sorted on each row.
Then you can split the table into separate String rows and use regular expressions on each row to match both HW and IP Adress. And you're done.
Java provides no direct way to query the MAC address of a host in your network, as this is abstracted away by Java's socket libraries.
In a way, this makes sense, because the MAC address of a host actually says very little. There is no such thing as "the" MAC address of a host.
Put both of these issues together, and that means that one host may have many different MAC addresses (if it has more than one NIC), and one MAC address may represent many different hosts (if traffic passes through a router).
Assuming you know all this and you still need to get the MAC address of a host, the only way to do that in Java is by "going native":
system_profile
command.system_profile
probably exists.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With