Filtering/sanitizing IP addresses lists on command line

Sometimes You have to obtain via command line on a list of IP addresses and you need to be sure it will not contain any IP addresses assigned to the machine You’re working on – especially, when You’re planning to use this list during automated modification of firewall rules.

On a DirectAdmin controlled server using the content of /usr/local/directadmin/data/admin/ip.list will probably be the fastest way. Running:

ifconfig \
    | grep -v \
        -Ff /usr/local/directadmin/data/admin/ip.list

should show the normal output of ifconfig without all lines containing the IP addresses we don’t want to have on our list. But remember, /usr/local/directadmin/data/admin/ip.list may not contain all important IP addresses – 127.0.0.1 is not found there.

And without DirectAdmin there are many different ways of obtaining current machines IP addresses:

ifconfig | grep "inet addr" | cut -d':' -f2 | cut -d' ' -f1

or

ifconfig |grep "inet addr" | sed 's/\:/ /' | awk '{print $3}'

And now all together, create a regular expression matching local IP addresses:

ifconfig | grep "inet addr" | cut -d':' -f2 | cut -d' ' -f1 \
    | tr "\n" "|" | sed -e 's/\./\\./g' -e 's/^/(/g' -e 's/|$/)/g'

Leave a Reply