Created
April 23, 2014 04:13
-
-
Save mgold/11202521 to your computer and use it in GitHub Desktop.
Find the smallest CIDR block that contains two IPAddrs, in Ruby.
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
require "ipaddr" | |
class IPAddr | |
# Returns the ipaddr representing the smallest CIDR block that includes both | |
# ipaddrs. | |
def union(other) | |
addr = @addr | |
coerced = coerce_other(other).to_i | |
prefixlen = self.ipv4? ? 32 : 128 | |
while addr != coerced | |
addr = addr >> 1 | |
coerced = coerced >> 1 | |
prefixlen -= 1 | |
end | |
return self.clone.mask!(prefixlen) | |
end | |
end | |
# whois 1.64.0.0 | |
inetnum = "1.164.0.0 - 1.164.255.255" | |
a1, a2 = inetnum.split("-").map{|s| IPAddr.new s.strip} | |
puts a1.union(a2).inspect | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This uses an O(n) algorithm. In theory you could use binary search but I'm not sure if it would be worth it.