Thanks guys, and in the meantime, I've finished the rest of the program. Seems to work perfectly and I'm gonna post it here for everyone to see (maybe it'll be useful to someone.. who knows). Also I'll take a look at what Bethany suggested. But for now, using arithmetic division and modulo worked xD
Here's the code if anyone wants it. When running it from a command line type perl than whatever you name the file followed by arguments which go: IP address to subnet, current mask, number of hosts/subnets, "hosts" or "subnets" depending on what you want and in the end, the maximum number of subnets to display. It then displays the new mask, and the subnets including their first and last IP address.
sub dec_to_bin
{
my $number= $_[0];
my $position= $_[1];
while($number!= 0)
{
$adress_bin[$position]= $number % 2;
$position--;
$number= int($number/ 2);
}
}
sub bin_to_dec
{
my $sum= 0;
my $mult= 128;
my $i;
for $i($_[0] .. $_[1])
{
$sum+= $mult* $adress_bin[$i];
$mult/= 2;
}
return $sum;
}
sub dec_print
{
print bin_to_dec(0, 7), ".", bin_to_dec(8, 15), ".", bin_to_dec(16
+, 23), ".", bin_to_dec(24, 31);
}
sub num_of_bits
{
my $i= 2;
my $number= 2;
while($number< $_[0])
{
$i++;
$number= (2** $i)-2;
}
return $i;
}
$adress_dec= $ARGV[0];
$old_mask= $ARGV[1]-1;
$num_of= $ARGV[2];
$sub_host= $ARGV[3];
$max_to_show= $ARGV[4];
@adress_dec= split(/\./, $adress_dec);
for $i (0 .. 31)
{
$adress_bin[$i]= 0;
}
dec_to_bin($adress_dec[3], 31);
dec_to_bin($adress_dec[2], 23);
dec_to_bin($adress_dec[1], 15);
dec_to_bin($adress_dec[0], 7);
if($sub_host eq "hosts")
{
$new_mask= 31- num_of_bits($num_of);
}
else
{
$new_mask= $old_mask+ num_of_bits($num_of);
}
print "New mask: ", $new_mask+1, "\n\n";
$to_show= (2**($new_mask- $old_mask))-2;
if($to_show> $max_to_show)
{
$to_show= $max_to_show;
}
for $i(1 .. $to_show)
{
$temp= $i;
$i2= $new_mask;
while($temp!= 0)
{
$adress_bin[$i2]= $temp % 2;
$i2--;
$temp= int($temp/ 2);
}
for $i2($new_mask+1 .. 31)
{
$adress_bin[$i2]= 0;
}
dec_print();
print "\n\t";
$adress_bin[31]= 1;
dec_print();
print "\n\t";
for $i2($new_mask+1 .. 31)
{
$adress_bin[$i2]= 1;
}
$adress_bin[31]= 0;
dec_print();
print "\n";
}
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.