I have a log file that lists whitelisted IP ranges in this manner:217.29.0.0-217.29.255.255,204.12.0.0-204.12.255.255,198.54.223.0-198.54.223.255,I am also working on a bash script which, amongst other things, needs to check this logfile and determine if a specified IP is whitelisted.In the case of IP 204.12.5.10, for instance, how would I use the log file with the specified ranges to determine whether that IP is part of a range in that file?
Check whether an IP belongs to a specific range
bash;scripting;ip
The useful thing to remember with IP addresses is that they're actually just representations of a 32bit number. So you can convert them to a decimal by multiplying the octets as base 256. E.g.:217.29.0.0 == 216 * 256 ^ 3 + 29 * 256 ^2 + 0 * 256 ^1 + 0 * 256 ^ 0           == 3640655872So given a range like the above - first convert them both, such that you've got a start and end. Then compare any incoming IPs to see if they 'fit'. So something like this (illustrating algorithm): #!/usr/bin/env perluse strict;use warnings;my $ip_to_check = 204.12.5.10;my $dword       = 0;for ( split( '\.', $ip_to_check ) ) { $dword *= 256; $dword += $_ }print Checking $dword\n;while (<DATA>) {    my ( $start, $finish ) = m/([\d\.]+)/g;    my $start_dword = 0;    for ( split '\.', $start ) { $start_dword *= 256; $start_dword += $_ }    my $end_dword = 0;    for ( split '\.', $finish ) { $end_dword *= 256; $end_dword += $_ }    print Range:\n;    print \t$start \t=> $start_dword\n;    print \t$finish \t=> $end_dword\n;    print $ip_to_check is in $_\n if $dword >= $start_dword and $dword <= $end_dword;}__DATA__217.29.0.0-217.29.255.255,204.12.0.0-204.12.255.255,198.54.223.0-198.54.223.255,Could quite easily do that as a 'check script' - by reading a file (rather than DATA) and getting $ip_to_check from STDIN). (note - as pure perl could be turned into a one liner fairly easily, or a script to call. Or re-written - I daresay you could do this with expr easily enough). 