PDA

View Full Version : Inconsistent behavior


jimhoyt
03-15-2004, 11:15 AM
I'm a Unix newbie trying to modify a dynamic DNS script and am getting a (sometimes) good answer from the following snippet:
ifconfig en0 | grep inet | awk '{print $2}' | awk -F : '{print $2}'
Any ideas would be great!

Jim

PS - The script is for Sitelutions.com which is a super service. Domain registration for less than $9 per year!

yellow
03-15-2004, 11:23 AM
Sorry, I won't be any help wuth your script, but can mention an alternative. You could always write a script that gets the data from a curl'd shot at http://www.whatismyip.com .. Others have asked the same question and you should be able to find the posts on here using the Search function (http://forums.macosxhints.com/search.php?s=).

mervTormel
03-15-2004, 01:13 PM
assuming you want the IP address of en0...

$ ifconfig en0 | grep inet
inet 192.168.1.10 netmask 0xffffff00 broadcast 192.168.1.255

$ ifconfig en0 | grep inet | cut -d" " -f2
192.168.1.10

why the awk parse about the colon (:) ? leaving the second awk pipe off returns the same as cut, here.

trevor
03-15-2004, 01:22 PM
Unfortunately, that will "fail" (or actually, it will also give you your IPv6 IP) if you have inet6 in your ifconfig.

% ifconfig en0 | grep inet
inet6 fe80::230:65ff:fe4f:ec7a prefixlen 64 scopeid 0x4
inet 192.168.0.100 netmask 0xffffff00 broadcast 192.168.0.255
% ifconfig en0 | grep inet | cut -d" " -f2
fe80::230:65ff:fe4f:ec7a
192.168.0.100


A small variation that will fix this issue is grepping for "inet " (note the space)

% ifconfig en0 | grep "inet " | cut -d" " -f2
192.168.0.100

Trevor

jimhoyt
03-15-2004, 01:54 PM
Thanks all,

This pretty much does the trick for non-router/NAT situations:
function getIP () {
IPADDR=`ifconfig en0 | grep "inet " | cut -d " " -f2`
if [ "$IPADDR" = "" ]; then
echo "Error: No connection. Check your cable."
exit 0
else
if [ "$IPADDR" = "inet" ]; then
echo "Error: Interface not enabled"
exit 0
else
echo $IPADDR
fi
fi
}

getIP

Your help is much appreciated. 'course I'm very open to opinions on this. This bash stuff is _different_ ! Thanks again.

Jim