[RndTbl] determine IP address in linux

Adam Thompson athompso at athompso.net
Sun Mar 24 11:49:37 CDT 2013

There is (AFAIK) no generic, portable, standardized solution.
1. No UNIX system is guaranteed to have networking at all, never mind 
2. POSIX doesn't cover networking configuration commands (that I can 
find, anyway)
3. LSB doesn't cover networking configuration commands (that I can 

To be portable across multiple versions, you have to check for various 
1. existence of 'ip' command from iproute/iproute2 (and acceptable 
2. if not, then existence of ifconfig (and at least two forms of 
output) isn't guaranteed either

There *is* one standardized way to get the info on any Linux kernel 
from the last ~10 years, but you can't do it from shell.  Use 
AF_NETLINK, which is what ip(8) does internally.  Bad design, IMHO... 
should have been exported via /proc or /sys to conform to the 
"everything is a file" paradigm.

See attached for how you would portably handle the four cases I'm aware 
of in bash.  Note that there are some bash-specific constructs in there. 
It's probably runnable under ksh, but the new-style conditionals 
definitely don't run in dash(1).

Obviously, the script could be made a LOT more compact.


On 2013-03-23 22:40, Trevor Cordes wrote:
> Seems simple.  What's the best way (in a script) to get the IP 
> address of
> an ethernet interface (in linux).  For instance eth0.
> I used to have (perl, but also applies as a bash solution):
> $eip=`/sbin/ifconfig $int | grep 'inet addr' | awk '{print \$2}' |
> sed -e 's/.*://'`
> But the latest upgrade from F16 to F17 broke this (now the line 
> contains
> "inet" but not "inet addr".
> So I started thinking of finding the most standardized way that
> (hopefully) won't change after a future kernel upgrade :-)
> It would seem that the less field parsing done, the better, as 
> keywords
> and field position aren't guaranteed.
> Looks like ifconfig is now deprecated (according to man ifconfig).  
> So now
> I'm doing:
> $eip=`ip -o -4 addr list eth0 | awk '{print \$4}'`
> That works now, but it still has a output format-dependent 
> requirements.
> I looked for /sys or /dev files, but can't find any that have ip4 
> addr.  I
> tried to find more options to whittle ip's output to give me just the
> address, no joy there.
> Ideas?
> PS: this is important as failures like this force me to drive out 
> onsite
> to headless boxes, some of which are 200km away.
> _______________________________________________
> Roundtable mailing list
> Roundtable at muug.mb.ca
> http://www.muug.mb.ca/mailman/listinfo/roundtable
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: getip_example.sh
URL: <http://www.muug.mb.ca/pipermail/roundtable/attachments/20130324/2c94bd0b/attachment.ksh>

More information about the Roundtable mailing list