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

Chris Green cl at isbd.net
Thu Jan 30 21:06:43 UTC 2020


On Thu, Jan 30, 2020 at 03:49:32PM -0500, Ken D'Ambrosio wrote:
> 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
> 
OK, strictly one should use 'hostname -I' according to the man page. 

> 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...
> 
Well, on all my systems, it returns the LAN IP of the system.  Maybe
if one isn't connected to anything it returns the localhost address.


> # 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.)
> 
Yes, all of which confirms my 'messy' comment at the start when I
asked the question! :-)

-- 
Chris Green




More information about the ubuntu-users mailing list