Get External/Local Ip regardless to Network Device in Linux

#!/bin/bash
# Date:     January 2015
# Author:  Hanine HAMZIOUI
# Usage:    Get the Machine IP. Commands are fallbacks
#           Just do: $~ bash ip.sh or bash.sh local/private/host
 
COM1=$(dig +short myip.opendns.com @resolver1.opendns.com 2>/dev/null)
COM2=$(hostname -i 2>/dev/null)
COM3=$(ip route show 2>/dev/null | grep src | grep -vE 'eth1.*|lo' |  awk -Fsrc '{print $2}' | sed -e 's/ //g')
COM4=$(curl -s monip.org 2>/dev/null | grep -o -E '([0-9]+\.){3}[0-9]+')
COM5=$(host `hostname -f 2>/dev/null` | awk -F[aA]ddress '{print $2}' | sed 's/ //g')
COM6=$(for i in eth0 em1 bond0; do inf=`ip -4 addr show dev $i 2>/dev/null | grep inet -m1 | cut -d/ -f1 | awk '{ print $2}'`;if [[ "$inf" =~ [0-9][0-9]?* ]]; then echo "$inf";fi ;done)
if [[ "$1" =~ local ]] ;then
    COM1=$COM3
fi
if [[ "$1" =~ private ]] ;then
    COM1=$COM2
fi
if [[ "$1" =~ host ]] ;then
    COM1=$COM5
fi
IP=''
validip()
{
    local  ip=$1
    local  stat=1
 
    if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
        OIFS=$IFS
        IFS='.'
        ip=($ip)
        IFS=$OIFS
        [[ ${ip[0]} -le 255 && ${ip[1]} -le 255 && ${ip[2]} -le 255 && ${ip[3]} -le 255 ]]
        stat=$?
    fi  
    if [ "$stat" -eq 0 ]; then
        echo $IP
    else
        echo $stat
    fi  
    return $stat
}
if [ -n "${COM1}" ];then
    IP=${COM1}
    eval validip $IP
    exit
fi
 
if [ -n "${COM2}" ];then
    IP=${COM2}
    eval validip $IP
    exit
fi
if [ -n "${COM3}" ];then
    IP=${COM3}
    eval validip $IP
    exit
fi
if [ -n "${COM4}" ];then
    IP=${COM4}
    eval validip $IP
    exit
fi
 
if [ -n "${COM5}" ];then
    IP=${COM5}
    eval validip $IP
    exit
fi
if [ -n "${COM6}" ];then
    IP=${COM6}
    eval validip $IP
    exit
fi
exit
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s