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

ibrahim picture ibrahim · Dec 8, 2012 · Viewed 20.1k times · Source

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.

Answer

gniourf_gniourf picture gniourf_gniourf · Dec 8, 2012

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"