Question

I have a file whose contents are like this

 164.91.32.120 164.91.32.123
 164.91.32.127 164.91.32.128
 164.91.32.131 164.91.32.132
 164.91.32.137 164.91.32.200
 164.91.33.20 164.91.33.161

Any way to find out all the IPs between the ranges and print the output in a file like this using a shell script

 164.91.32.120
 164.91.32.121
 164.91.32.122
 164.91.32.123
 164.91.32.127
 164.91.32.128
 164.91.32.131

and so on...

No correct solution

OTHER TIPS

You can convert beginning and ending IP to 32 bit numbers, iterate over their range by +1 increments, and convert resulting numbers back to IP format.

IPv4 addresses are simply 32-bit numbers.

sub ip_to_num { unpack 'N', pack 'C4', split /\./, $_[0] }
sub num_to_ip { join '.', unpack 'C4', pack 'N', $_[0] }

say num_to_ip($_) for ip_to_num($ip_from) .. ip_to_num($ip_to);

What implementations have you tried so far? Do you have any code that you can show?

You can always use Perl to read in the text file, split on the space / tab character you have between the IP ranges and then string parse.

Example:

#!/usr/bin/perl
use strict;
use warnings;

open(INPUT_FILEHANDLE, "myfile.txt") or die("$!");
open(OUTPUT_FH, ">>outfile.txt") or die("$!");
while(chomp(my $line = <INPUT_FILEHANDLE>)) {
    my @split = split(" ", $line);
    my @octets_first = split(".", $split[0]);
    my @octets_second = split(".", $split[1]);
    my $subnet = $split[0].$split[1].$split[2];
    my $difference = $octets_second[3] - $octets_first[3];
    for(my $i = $octets_first[3]; $i < $difference; $i++) {
        print OUTPUT_FH $subnet.$i;
        print OUTPUT_FH "\n";
    }
}
close(INPUT_FILEHANDLE);
close(OUTPUT_FH);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top