Your skill will accomplish what the force of many cannot |
|
PerlMonks |
calculate subnet helpby Anonymous Monk |
on Aug 26, 2011 at 14:15 UTC ( [id://922645]=perlquestion: print w/replies, xml ) | Need Help?? |
Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:
I'm hoping some golfers can help me with this. I'm trying to calculate a subnet based on an IP and mask. 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);
Back to
Seekers of Perl Wisdom
|
|