amanada.williams amanada.williams - 1 year ago 201
Linux Question

How to get the IP address of a server using bash

Pull the IP address from the server. However, the issue comes into play that dedicated and VPS are very different. What is the best or most ideal way to pull and do a check and print the IP Address?

I guess I could do a check with the following?

[email protected]]# /sbin/ifconfig venet0:0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'
[email protected]]# /sbin/ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'
eth0: error fetching interface information: Device not found

Answer Source

To get the IP address of your server whether it be a VPS or not you can do the following:


a="`netstat -i | cut -d' ' -f1 | grep eth0`";
b="`netstat -i | cut -d' ' -f1 | grep venet0:0`";

if [ "$a" == "eth0" ]; then
  echo "eth0 found"
  ip="`/sbin/ifconfig eth0 | awk -F':| +' '/inet addr/{print $4}'`";
elif [ "$b" == "venet0:0" ]; then
  echo "venet found"
  ip="`/sbin/ifconfig venet0:0 | awk -F':| +' '/inet addr/{print $4}'`"; 

echo $ip;

Hope this helps.

Hat tip to jwpat7 for providing the awk command that is more succinct than the grep, cut, awk.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download