Skip to content

Instantly share code, notes, and snippets.

@epitron
Created November 11, 2015 23:46
Show Gist options
  • Select an option

  • Save epitron/ace008dcaa467c875991 to your computer and use it in GitHub Desktop.

Select an option

Save epitron/ace008dcaa467c875991 to your computer and use it in GitHub Desktop.
def ip_to_int(ip)
ip.split(".").map(&:to_i).reverse.each_with_index.map {|n,i| n << (i*8) }.reduce(:+)
end
def range_to_ip_and_mask(range)
ip, width = range.split("/")
mask = 0xffffffff >> width.to_i
[ip_to_int(ip), mask]
end
def int_to_ip(n)
(0..3).map do |current_byte|
(n >> (8 * current_byte)) & 0xFF
end.reverse.join(".")
end
def in_range?(ip, range)
ip = ip_to_int(ip)
net, mask = range_to_ip_and_mask(range)
ip & ~mask == net & ~mask
end
p in_range?("10.2.3.5", "10.2.3.4/5")
p in_range?("128.2.3.5", "10.2.3.4/5")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment