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])'

2 thoughts on “grep ip address, grep regular expression

  1. Joe

    As intresting as this regex is.. my question is why would you ever need to run this command as root.. the adv user should be able to user this command

  2. Brendan Skoreyko

    Yes you are correct. For this example I just ran the command as root. Any user with SU permissions can run this command. However if you are a regular user you cannot run the ifconfig command (this command relates to Red Hat, Fedora, Cent OS).

Leave a Reply

Your email address will not be published. Required fields are marked *

*