There is (AFAIK) no generic, portable, standardized solution. Reasons: 1. No UNIX system is guaranteed to have networking at all, never mind TCP/IP. 2. POSIX doesn't cover networking configuration commands (that I can find, anyway) 3. LSB doesn't cover networking configuration commands (that I can find)
To be portable across multiple versions, you have to check for various things: 1. existence of 'ip' command from iproute/iproute2 (and acceptable output) 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.
-Adam
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@muug.mb.ca http://www.muug.mb.ca/mailman/listinfo/roundtable