How to get the MAC address of the 'local' system given the IP address?

Karl Auer kauer at biplane.com.au
Fri Jan 31 13:19:09 UTC 2020


On Thu, 2020-01-30 at 17:22 +0000, Chris Green wrote:
> ... but I can't find a neat way of getting the corresponding MAC
> address and company information as for arp-scan. The MAC address can
> be obtained using ifconfig or ip but it's an exercise in frustration
> trying to extract the relevant bits:-

You have all the bits you need, and it's not that hard to extract them.

- interface address from ip (ip addr show)
- interface MAC from ip (ip link show).
- MAC address mappings from publicly available lists

curl https://gitlab.com/wireshark/wireshark/raw/master/manuf -o
macs.txt

arp-scan has its own list in /usr/share/arp-scan/ieee-oui.txt, but my
version is dated 2014! Admittedly I am still running 16.04LTS.

Anyway, a bit of grepping and cutting, and you should be able to get
what you want or close to it:

# What interface?
I="eth0"

# Get the MAC address of the interface
MAC=`ip addr show dev $I |      \
   grep link/ether |            \
   cut -d\  -f6`

# If there is no MAC (shouldn't happen) complain
if [ -z "$MAC" ] ; then
   echo "No MAC address found on interface $I. Stopping."
   exit 1
fi

# Get the IPv4 address on the interface. May not be one.
IPA=`ip addr show dev $I |      \
   grep -v inet6 |              \
   grep inet |                  \
   cut -d\  -f6 |               \
   cut -d\/ -f1`

# Grab the first three parts of the MAC address
OUI=`echo $MAC |                \
   cut -d\: -f1,2,3`

# If we have no OUI, no point looking for details
if [ -z "$OUI" ] ; then
   CMP=""
else
   # Otherwise look for the company details
   CMP=`grep -i "^$OUI" macs.txt | \
      cut -f3`
fi

# Convert missing bits to something helpful
if [ -z "$IPA" ] ; then
   IPA="no-ip"
fi

if [ -z "$CMP" ] ; then
   CMP="no-detail"
fi

# Finally output the details
echo "$IPA $MAC $CMP"

If you want to wrap that up in a loop and do it for all local
interfaces, this'll do it:

LINKS=`ip link show |    \
     grep -v link | \
     tr -d " " |    \
     cut -d\: -f2`
for i in $LINKS ; do
{
   ... the above ...
}
done

To avoid interfaces that are not active, just skip those where $IPA is
"no-ip".

As always, the above has NOT been tested, so use at your own risk etc
etc.

Regards, K.

-- 
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Karl Auer (kauer at biplane.com.au)
http://www.biplane.com.au/kauer
http://twitter.com/kauer389

GPG fingerprint: 8D08 9CAA 649A AFEF E862 062A 2E97 42D4 A2A0 616D
Old fingerprint: A0CD 28F0 10BE FC21 C57C 67C1 19A6 83A4 9B0B 1D75






More information about the ubuntu-users mailing list