Monthly Archives: March 2010

grep ip address, grep regular expression

Here is how I use grep to find an IP address, using a regular expression:
(I am using CentOS which is a Redhat based OS – so I don’t expect this to work on all distributions. I am also running the “ifconfig” command as root)

# using the ifconfig command as root user and piping output into grep
ifconfig | grep -E '.*([0-9]{1,3}[\.]){3}[0-9]{1,3}*'

The above grep statement isn’t the best way to find the IP address but it will work.  Really using grep and regular expressions to find the IP address should be more accurate, the above grep allows for any number and we know that an IP address cannot be 999.999.999.999 – it must be 255.255.255.255.

Here is a better way:

# using the ifconfig command as root user and piping output into grep
ifconfig | grep -E '.*((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])'