in reply to Automatic IP address Generation

The dotted form of IP addresses is just a representation of a 32-bit number. You'll have better luck working with an IP address as a number.
use Socket qw( inet_aton inet_ntoa ); sub fr_dotted { unpack 'N', inet_aton @_ ? $_[0] : $_ } sub to_dotted { inet_ntoa pack 'N', @_ ? $_[0] : $_ } my $next = fr_dotted('100.1.3.41'); my $max = fr_dotted('100.1.3.50'); die if $next > $max; my $new = $next++; print(to_dotted($new), "\n");

Update: Had inet_aton where inet_ntoa should have been used.

Replies are listed 'Best First'.
Re^2: Automatic IP address Generation
by ajd335 (Novice) on Jul 30, 2008 at 15:59 UTC
    Hi Ikegami, Thanks for your help. My result.txt file contains data like
    host1-001 10.22.33.22 host2-001 10.33.68.254
    something like above , And as i told you before I want to have update that with
    host1-001 10.1.3.41 host2-001 10.1.3.42
    so in your above code , where should i give the result.txt( which contains old IP as argument)...I really dont have idea. Thanks,
Re^2: Automatic IP address Generation
by ajd335 (Novice) on Jul 30, 2008 at 19:42 UTC
    Hi Ikegami , I have tried out the below.
    #!/usr/bin/perl open(HANDLE , "result3.txt") || die("Could not open file!"); while(<HANDLE>) { chomp; use Socket qw( inet_aton inet_ntoa ); sub fr_dotted { unpack 'N', inet_aton @_ ? $_[0] : $_ } sub to_dotted { inet_aton pack 'N', @_ ? $_[0] : $_ } my $next = fr_dotted('100.1.3.41'); my $max = fr_dotted('100.1.3.50'); die if $next > $max; my $new = $next++; $new1 = to_dotted($new); print $new1; } close(HANDLE);
    But that does not give me the desired results. Am I doing it correct ?
      #!/usr/bin/perl use strict; use warnings; use Socket qw( inet_aton inet_ntoa ); sub fr_dotted { unpack 'N', inet_aton @_ ? $_[0] : $_ } sub to_dotted { inet_ntoa pack 'N', @_ ? $_[0] : $_ } my $next = fr_dotted('100.1.3.41'); my $max = fr_dotted('100.1.3.50'); while (<>) { chomp; my ($host) = split(' '); die("Exceed max\n") if $next > $max; my $addr = $next++; print($host, ' ', to_dotted($addr), "\n"); }
      renum.pl infile > outfile -or- perl -i.bak renum.pl file

      Untested.

        Hi ikegami, I have removed the blank space part. But , One more thing , I also need to check if the IP is already assigned someone or not..If it is assigned to some workstation , then that IP add should be skipped and the next available IP address should be taken. Thanks,
        Hi Ikegami , Yes it gives me answer . But the thing is it is also taking the white spaces and also assign them the IP address. i mean it also take the blank lines into consideration