#!/bin/bash
exit_cleanup()
{
  if [ -f $tmpfile ]; then
     rm -f $tmpfile
  fi
  exit $1
}

usage()
{
   echo "usage: getipaddr [-6p] -i <network interface>" 
   echo "                 6      show IPV6 address only"
   echo "                 p      show prefix length for IPV6 address"
   echo "                 i      interface name to query"
   exit 1

}
if [ $# = 0 ]; then
   usage
fi
ipv="ipv4"
prefix=""
nwif=""

while getopts 'i:46p?' optname; do
   case "$optname" in
      i) nwif="$OPTARG";;
      6) ipv="ipv6";;
      p) prefix="yes";;
      \?) usage ;;
   esac
   noopt=0
done
if [ "$nwif" == "" ]; then
   usage
fi

tmpfile=/tmp/nwif$$
LANG=en_US /sbin/ifconfig $nwif > $tmpfile
if [ "$ipv" == "ipv6" ]; then
  # only interested in IPV6
  ip=`cat $tmpfile | /usr/bin/grep "inet6 addr" | /usr/bin/grep "Scope:Global" 2>/dev/null`
  if [ $? -ne 0 ]; then
     echo "No IP Address found."
     exit_cleanup 1
  fi
  ip=${ip%% Scope*}
  ip=${ip##*addr: } 
  # Strip prefix length
  if [ "$prefix" != "yes" ]; then
    ip=${ip%%/*} 
  fi
else
  # see if there is an IPV4 IP first
  ip=`cat $tmpfile | /usr/bin/grep "inet addr" 2>/dev/null`
  if [ $? -ne 0 ]; then
    # Now find IPV6 information
    ip=`cat $tmpfile | /usr/bin/grep "inet6 addr" | /usr/bin/grep "Scope:Global" 2>/dev/null`
    if [ $? -ne 0 ]; then
       echo "No IP Address found."
       exit_cleanup 1
    fi
    # dealing with ipv6 ip
    ip=${ip%% Scope*}
    ip=${ip##*addr: } 
    # Strip prefix length
    if [ "$prefix" != "yes" ]; then
      ip=${ip%%/*} 
    fi
  else
  # Reached this point we have ipv4 ip
    ip=`echo $ip | cut -d':' -f2 | cut -d' ' -f1`
  fi
fi
rm -f $tmpfile
echo $ip

