Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:
Calculation of subnet:
1)Find first non-255 or non-0 octet of mask.
2)Copy all octects to the left of the first non 255/0 octect of the mask to the subnet.
3) Write a 0 for remaining octects AFTER the first non 255/0 octect
4) Subtract 256 minus the octect with the first non 255/0. Then find out how many times that sum can go into that same octect of the IP address octect. Multiply the sum and number of times it can go into the IP. (this will be the result for the first non 255/0 octect).
Example:
IP: 192.168.190.128
Mask: 255.255.255.224
For the subnet, you copy over the first 3 octects of the mask because they are 255 or 0.
Subnet: 255.255.255 To find the first special octect (which is the 4th octect in this example with 224), we do: 256 - 224 = 32.
From 32 we find out how many times it can go into the same IP octect without going over the ip (32 goes into 128 evenly this time 4 times. So the result is 128).
Subnet final: 255.255.255.128
If the last IP octect was 127 in this example the math would be: 256 - 224 = 32. 32 goes into 127 3 times. 32 X 3 = 96.
Final subnet: 255.255.255.96
--------------------------------
That covered I know there's a simple way of doing this. I made it more difficult than it had to and it works for the most part but I want to make it cleaner and shorter.
Can you help me?
Note: I'm asking the IP and Mask at the command line then converting them into an array split on periods.
Ie: $ip = <STDIN>; @ip= split(/\./, $ip);
my $oct_cnt = -1; for (1 .. 4) { $oct_cnt++; if ($mask[$oct_cnt] =~ m/255/ || $mask[$oct_cnt] =~ m/0/) { #print "skipping, $oct_cnt is 255 or 0"; push(@sub, $mask[$oct_cnt]); } else { #print "found non 255 or zero at $oct_cnt with $mask[$oct_cnt]" +; my $sum = 256 - $mask[$oct_cnt]; my $rem = $ip[$oct_cnt] / $sum; $rem =~ m/([0-9]+)\./; my $clean_rem = $1; push(@sub, $clean_rem * $sum); # determine what octet we are, set remainders to 0 if($oct_cnt+1 < 4) { for ($oct_cnt+1 .. 4) { push(@sub, $ip[$oct_cnt+1]); } } last if;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: calculate subnet help
by sulfericacid (Deacon) on Aug 26, 2011 at 15:39 UTC | |
|
Re: calculate subnet help
by fs (Monk) on Aug 27, 2011 at 17:09 UTC |