Tuesday, December 28, 2021

[SOLVED] Is there any better way to get mac address from arp table?

Issue

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.


Solution

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"


Answered By - gniourf_gniourf