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

Tom H tomh0665 at gmail.com
Sat Feb 1 15:12:43 UTC 2020


On Fri, Jan 31, 2020 at 2:21 PM Karl Auer <kauer at biplane.com.au> wrote:
>
> 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`

For this "-f6" and the one below, it's better to trim the leading
whitespace, if only to develop good habits.

Using sed, for example

ip a sh dev wlan0 | sed -n -e 's/^[[:blank:]]*//' -e '/link\/ether/p'
| cut -d\  -f2
or
ip a sh dev wlan0 | sed -n -e 's/^[ \t]*//' -e '/link\/ether/p' | cut -d\  -f2

If "moreutils" is installed (and you haven't assigned multiple
addresses with "ip a ..." if you want to list ip addresses [1]), you
can use "ifdata".

$ ifdata -h
...
-pa Print out the address
-pn Print netmask
-pN Print network address
-pb Print broadcast
-pm Print mtu
-ph Print out the hardware address
...

[1] You have to have one ip address per "alias" in order to get them via ifdata

# ip a add 192.168.0.102/24 label wlan0:1 dev wlan0
# ip a add 192.168.0.103/24 dev wlan0
# ip a sh dev wlan0 | grep "inet "
    inet 192.168.0.101/24 brd 192.168.0.255 scope global noprefixroute wlan0
    inet 192.168.0.102/24 scope global secondary wlan0:1
    inet 192.168.0.103/24 scope global secondary wlan0
# ifdata -pa wlan0
192.168.0.101
# ifdata -pa wlan0:1
192.168.0.102

You can't output ".103" because it's an unlabelled secondary address.


> # 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".




More information about the ubuntu-users mailing list