Getting the IP address in unix server

Hi,

I want to know the IP of my Unix server in my script programming.

Below are the my trial and i didn't find anything useful for me.because i want only IP.

hostname -> Giving the name of the server and
hostanme -i -> Giving the error message that..i am not super user.

ipConfig -> Giving the IP address with lot of data.

Pls give me some idea, where i can get my server IP.

Thanks & Regards
Balamani

Something like this perhaps?

grep -w `hostname` /etc/hosts | awk '{print $1}'
ifconfig -a eth0 | grep "inet addr"| awk '{print $2}' | sed 's/addr://'

that would work fine for regular linux server.

Thanks

Hi,

I am able to get the IP of my server from command prompt, but when i put the same in my script its give the output has hostname.

#!/usr/bin/bash
SERVER_IP=`grep -w `hostname` /etc/hosts | awk '{print $1}'`
echo $SEREVR_IP

Why ?

The problem is that different UNIX flavours use different names for the devices: what Linux or SunOs calls "eth0" is called "en0" in AIX, etc. Furthermore, you can never be sure that "en0" or "eth0" - that is: the first interface - is the one with hostname on it. In a PC this might be the case, in an LPAR in a POWER5+-Box this is most likely wrong, because "en0" is usually a service interface for booting, administration, etc.

Therefore there might be different ways to achieve your goal, all with some shortcomings. Choose your poison :wink: :

1) Issue "uname -a" and find out on which system you are running, then issue the appropriate command for the respective OS to determine the interfaces address.

1a) It might be a good idea to encapsulate this in a script function. Something like (this is just a sketch):

function get_main_ip

typeset OS=$(uname -a | cut -d' ' -f1)
typeset IP=""

case "$OS" in
     AIX)
          IP=$( ifconfig en0 | sed '<remove_unnecessary_info>' )
          ;;

     Linux)
          IP=$( ifconfig eth0 | sed '<remove_other_info>' )
          ;;

     SunOS)
          IP=$( ifconfig ent0 | sed 'whatever_is_necessary_here' )
          ;;

     *)
          print -u2 "do not know how to handle this OS".
          ;;
esac

print - "$IP"

return 0
}

2) find out the hostname (via "hostname") and find then the interface which resolves to this hostname by the above shown method. You must still determine which OS you run on.

I hope this helps.

bakunin

Try this and replace "bge0" with the name of your interface:

var1=`netstat -in | grep bge0 | awk '{ print $4 }'`

# echo $var1
192.168.1.1

You can't nest backquotes (the shell has no way of knowing which ones are inside others, i.e. it sees `grep -w ` as one set, and ` /etc/hosts | awk '{print $1}'` as another set. That's why it's safer to use the $( command ) syntax:

#!/usr/bin/bash
SERVER_IP=$(grep -w $(hostname) /etc/hosts | awk '{print $1}')
echo $SEREVR_IP

No need for grep and awk:

var1=`netstat -in | awk '/bge0/ { print $4 }'`