Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(bash) check if IP in subnet range file

I've a list of subnet range in a file:

2.32.0.0-2.47.255.255-255.240.0.0
2.112.0.0-2.119.255.255-255.248.0.0
2.156.0.0-2.159.255.255-255.252.0.0
2.192.0.0-2.199.255.255-255.248.0.0
...

(The file format is: {startip}-{endip}-{netmask})

I need check if an IP is included in one of the subnet in the file.

like image 414
Stefano Guarella Avatar asked Oct 21 '25 17:10

Stefano Guarella


2 Answers

You may use awk for that:

echo '127.0.0.0-127.255.255.255-255.0.0.0' | awk -F- '
    BEGIN { ip[1] = 127; ip[2] = 0; ip[3] = 0; ip[4] = 1; } 
    { split($1, startIp, "."); split($2, endIp, ".");
        for(i = 1; i <= 4; i++) {
            if(ip[i] < int(startIp[i]) || ip[i] > int(endIp[i]))
                break;
        }

        if(i == 5)
            print "matching line: ", $0; }'

IP for searching is initially set as array in BEGIN-clause as array. Each line is compared in for-cycle and if each octet laying between startIp and endIp, "matching line" is printed.


Some Python 3 gibberish relying on ipaddress module from 3.3 (available for 2.6/2.7:

python3 -c 'from ipaddress import ip_address as IP; list(
    map(print, ((startip, endip) for startip, endip, _ in 
            (ip.split("-") for ip in open("tmp/iplist.txt")) 
            if IP(startip) < IP("127.0.0.1") < IP(endip))))'

Which is actually one-liner version for following script:

import sys
from ipaddress import ip_address as IP

ip = IP(sys.argv[1])

with open(sys.argv[2]) as f:
    for line in f:
        startIp, endIp, _ = line.split('-')
        if IP(startIp) < ip < IP(endIp):
            print(line)

Which can be used like that:

$ python3 ipcheck.py 127.0.0.1 iplist.txt
like image 73
myaut Avatar answered Oct 23 '25 08:10

myaut


Try this:

BEGIN {
    FS="."
    ex = "false"
    split(address, ip, ".")
}
{
    split($0, range, "[-.]")
    for (i=1; i<5; i++) {
        if (ip[i] < range[i] || ip[i] > range[i+4])
            break;
        else if ((ip[i] > range[i] && ip[i] < range[i+4]) || i == 4)
            ex = "true"
    }
}
END {
    print ex
}

Invoke this awk script (checkIP.awk) like this:

$ awk -v address="2.156.0.5" -f checkIP.awk /path/to/ip/ranges/file
true
$ awk -v address="0.0.0.0" -f checkIP.awk /path/to/ip/ranges/file
false
like image 31
ShellFish Avatar answered Oct 23 '25 07:10

ShellFish



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!