Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 540
ibrahim Avatar asked Dec 08 '12 13:12

ibrahim


People also ask

Can you use ARP to find MAC address?

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.

How do I find the MAC address of an IP ARP?

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.

Is ARP table same as MAC table?

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.

How does ARP protocol get the MAC address of a host knowing its IP address?

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.”


1 Answers

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"
like image 161
gniourf_gniourf Avatar answered Sep 20 '22 16:09

gniourf_gniourf