-
-
Save epitron/ace008dcaa467c875991 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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