Skip to content

Instantly share code, notes, and snippets.

@mgold
Created April 23, 2014 04:13
Show Gist options
  • Save mgold/11202521 to your computer and use it in GitHub Desktop.
Save mgold/11202521 to your computer and use it in GitHub Desktop.
Find the smallest CIDR block that contains two IPAddrs, in Ruby.
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
@mgold
Copy link
Author

mgold commented Apr 23, 2014

This uses an O(n) algorithm. In theory you could use binary search but I'm not sure if it would be worth it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment