-6

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...

Amistad
  • 7,100
  • 13
  • 48
  • 75

3 Answers3

1

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.

mpapec
  • 50,217
  • 8
  • 67
  • 127
1

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);
ikegami
  • 367,544
  • 15
  • 269
  • 518
0

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);
falconspy
  • 750
  • 3
  • 8
  • 22
  • @falconspy..i have not tried anything yet..was trying to write something in shell using the same logic..split the octets using the dots..subtract the last octets and then run a loop through the ips..I tried the perl script that you gave and got the following error.. # perl splitip Name "main::FILEHANDLE" used only once: possible typo at splitip line 7. readline() on unopened filehandle FILEHANDLE at splitip line 7. Use of uninitialized value in chomp at splitip line 7. – Amistad Dec 03 '13 at 14:21
  • @Amistad Please see my edit. I forgot to change the line while(chomp(my $line = )) to reflect the change I made - while(chomp(my $line = )). Please note I did not test my code either. – falconspy Dec 03 '13 at 14:41
  • 2
    @Amistad The question I linked above has the answer to your question, complete with code samples. That is what duplicate means: Its already been answered. So just go there and read the answer. – TLP Dec 03 '13 at 15:00