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

Ken D'Ambrosio ken at jots.org
Thu Jan 30 20:49:32 UTC 2020


On 2020-01-30 15:13, Chris Green wrote:

> Yes, I fear you may be right, an awk script may be the only way to do
> it.  I was just hoping for a neater/more elegant way to do it.
> 
> --
> Chris Green

I humbly submit you should *not* use "hostname -i":
ken at strider ~ $ hostname -i
127.0.1.1

Not sure where it pulls that from, but localhost is probably not what 
you're really wanting, so unless you understand the mechanics, there's 
more than one way to write a script.  What you probably *DO* really want 
is whatever interface your default gateway is using.  And, since I'm 
waiting for some virtual systems to build...

# First, I'm using netstat and grepping for the default gateway:
ken at strider ~ $ IF=`netstat -rn | grep "^0.0.0.0" | ruby -pe 
'$_=$_.split[-1]+"\n"'`

# Then, I'm getting the MAC, splitting it apart, taking the first three 
octets
# (used for manufacturer ID), and swapping the : with . to work with 
egrep.
ken at strider ~ $ MACPREFIX=`cat "/sys/class/net/$IF/address" | ruby -pe 
'$_=$_.split(":")[0..2].join(".")'`

# ANd, lastly, grepping the $MACPREFIX -- case insensitive -- from the 
oui.txt file.
ken at strider ~ $ egrep -i "$MACPREFIX" /usr/share/ieee-data/oui.txt
D8-FC-93   (hex)		Intel Corporate

I could write the whole thing up in my $LANGUAGEOFCHOICE, Ruby, but 
figured I'd at least make it command-lineable.  (Though I did use Ruby 
some, because, well, it's like Perl when it comes to string handling, 
but has OOP, and is great for admin tasks.  I pretty much ignore sed and 
awk.)

$.02,

-Ken




More information about the ubuntu-users mailing list