1

I need to check if an IP-address or a network is contained in other network, e.g. if '10.1.2.3' is in '10.0.0.0/8' or if '10.1.2.0/24' is in '10.0.0.0/8'. Currently I use python for this, e.g.:

if [ $(python -c 'import ipaddress; print(ipaddress.ip_address("10.1.2.3") in ipaddress.ip_network("10.0.0.0/8"))') == "True" ]; then
    echo "10.1.2.3 is in network 10.0.0.0/8"
fi

Is there a more concise/efficient way to do this in Bash?

  • You could do this entirely in bash, but it definitely would be less concise. – Thomas Dickey Jan 31 '16 at 14:42
  • Have you checked ipcalc ? – Valentin Bajrami Jan 31 '16 at 14:47
3

Here's not so concise bash script:

#!/bin/bash

v4dec() {
        for i; do
                echo $i | {
                        IFS=./
                        read a b c d e
                        test -z "$e" && e=32
                        echo -n "$((a<<24|b<<16|c<<8|d)) $((-1<<(32-e))) "
                }
        done
}

v4test() {
        v4dec $1 $2 | {
                read addr1 mask1 addr2 mask2
                if (( (addr1&mask2) == (addr2&mask2) && mask1 >= mask2 )); then
                        echo "$1 is in network $2"
                else
                        echo "$1 is not in network $2"
                fi
        }
}

v4test 10.1.2.3 10.0.0.0/8
v4test 10.1.2.0/24 10.0.0.0/8
v4test 192.168.0.1 10.0.0.0/8
v4test 10.0.0.0/7 10.0.0.0/8

Output:

10.1.2.3 is in network 10.0.0.0/8
10.1.2.0/24 is in network 10.0.0.0/8
192.168.0.1 is not in network 10.0.0.0/8
10.0.0.0/7 is not in network 10.0.0.0/8
  • Woah. Is there any chance, you could explain how this script works? – tjt263 Feb 15 '16 at 13:51
1

An awk script to do this for an ip addr in a network. I guess a little more would be needed for the network in a network part.

ipcalc -b 10.0.0.0/8 |awk -f check_ip.awk  ip="10.1.2.3"
ip is in range

script --

{
 if ($1 == "HostMin:") {
  split($2,add_min,".")
 } else if ($1 == "HostMax:") {
  split($2,add_max,".")
 }

} 

END{
   split(ip, ip_addr, ".")

   found = 1
   for(i=1; i<=4; i++) {
    if (ip_addr[i] < add_min[i] || ip_addr[i] > add_max[i]) {
        found = 0
        break
    }
   }            
    if (found)
     print "ip is in range"
    else
     print "ip is Not in range"

   }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.