Created
June 3, 2011 17:19
-
-
Save nevans/1006716 to your computer and use it in GitHub Desktop.
Just a simple CIDR to netmask conversion
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
def unpack_ip(packed_ip) | |
octets = [] | |
4.times do | |
octet = packed_ip & 0xFF | |
octets.unshift(octet.to_s) | |
packed_ip = packed_ip >> 8 | |
end | |
ip = octets.join('.') | |
end | |
def cidr_to_packed_ip(cidr) | |
(("1"*cidr)+("0"*(32-cidr))).to_i(2) | |
end | |
def cidr_to_netmask(cidr) | |
unpack_ip(cidr_to_packed_ip(Integer(cidr))) | |
end | |
require 'ipaddr' | |
def network_addr(ip_addr, cidr) | |
packed_ip = IPAddr.new(ip_addr).to_i | |
packed_cidr = cidr_to_packed_ip(cidr) | |
unpack_ip(packed_cidr & packed_ip) | |
end | |
describe "#cidr_to_netmask" do | |
[ | |
[32, "255.255.255.255"], | |
[27, "255.255.255.224"], | |
[24, "255.255.255.0"], | |
[17, "255.255.128.0"], | |
[16, "255.255.0.0"], | |
[ 8, "255.0.0.0"], | |
].each do |cidr, netmask| | |
specify "for #{cidr} should generate #{netmask}" do | |
cidr_to_netmask(cidr).should == netmask | |
end | |
end | |
end | |
describe "#network_addr" do | |
[ | |
["192.168.0.0", 32, "192.168.0.0"], | |
["192.168.0.10", 24, "192.168.0.0"], | |
["64.131.93.176", 27, "64.131.93.160"], | |
].each do |ip, cidr, network| | |
specify "for #{ip}/#{cidr} should generate #{network}" do | |
network_addr(ip, cidr).should == network | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment