Created
October 26, 2011 11:32
-
-
Save mwchambers/1316090 to your computer and use it in GitHub Desktop.
CIDR Subnet to Dot Notation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class SubnetCalc | |
def self.dot_notation_to_prefix(netmask) | |
netmask = ipv4_to_binary(netmask).split(//) | |
netmask.select{ |i| i == "1"}.length | |
end | |
def self.ipv4_to_binary(ipv4addr) | |
ia = ipv4addr.to_s.split('.') | |
if ia.size != 4 | |
raise "Invalid IP address" | |
end | |
output = "" | |
i = 1 | |
for octett in ia | |
output = output + "%08d" % octett.to_i.to_s(2) | |
i += 1 | |
end | |
return output | |
end | |
def self.cidr_to_binary(prefix) | |
binary="" | |
1.upto(prefix) { binary << "1" } | |
(prefix + 1).upto(32) { binary << "0" } | |
return binary | |
end | |
def self.cidr_to_dot_notation(prefix) | |
bin = SubnetCalc.cidr_to_binary(prefix) | |
a = bin[0,8].to_i(base=2).to_s | |
b = bin[8,8].to_i(base=2).to_s | |
c = bin[16,8].to_i(base=2).to_s | |
d = bin[24,8].to_i(base=2).to_s | |
return ("#{a}.#{b}.#{c}.#{d}") | |
end | |
end | |
puts SubnetCalc.dot_notation_to_prefix("255.255.255.0") | |
puts SubnetCalc.cidr_to_dot_notation(12) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment