I want to get a mac address from arp table by using ip address. Currently I am using this command
arp -a $ipAddress | awk '{print $4}'
This command prints what I want. But I am not comfortable with it and I wonder if there is any built-in way or more stable way to do this.
ARP (Address Resolution Protocol) is the protocol in charge of finding MAC addresses with IPs in local network segments. It operates with frames on the data link layer.
To see all the MAC addresses and their associated IP addresses, type “arp -a”. This command will list all the available MAC addresses in the system. The address on the left is the IP address, while the right is the MAC address. Find the corresponding IP address for the specific MAC address you want.
While there are a lot of similarities between these two tables, they serve different purposes. Most importantly, MAC and ARP tables work on different OSI model layers. ARP tables map a Layer 3 address to a Layer 2 address configuration, while MAC tables map a Layer 2 address to a Layer 1 (physical layer) interface.
ARP is the Address Resolution Protocol, used to translate between Layer 2 MAC addresses and Layer 3 IP addresses. ARP resolves IPs to MAC addresses by asking, “Who has IP address 192.168. 2.140, tell me.” An example of an ARP reply is “192.168. 2.140 is at 00:0c:29:69:19:66.”
You can parse the /proc/net/arp
file using awk
:
awk "/^${ipAddress//./\.}\>/"' { print $4 }' /proc/net/arp
but I'm not sure it's simpler (it saves one fork and a subshell, though).
If you want a 100% bash solution:
while read ip _ _ mac _; do
[[ "$ip" == "$ipAddress" ]] && break
done < /proc/net/arp
echo "$mac"
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