Created
May 31, 2017 23:32
-
-
Save dimonomid/f42204a56c72926ece4d27d365e9a63a to your computer and use it in GitHub Desktop.
Organization IPs
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
input = [ | |
[1, 0, 0, 0, 256, "AU-8a888ca7567d"], | |
[1, 0, 1, 0, 256, "CN-8173da22ea8b"], | |
[1, 0, 2, 0, 512, "CN-8173da22ea8b"], | |
[1, 0, 4, 0, 1024, "AU-4d44a4952b26"], | |
[1, 0, 8, 0, 2048, "CN-cc1064bf6999"], | |
[1, 0, 16, 0, 4096, "JP-9413fa3d189a"], | |
[1, 0, 32, 0, 8192, "CN-cc1064bf6999"] | |
] | |
class IPItem | |
attr_accessor :ip | |
attr_accessor :len | |
attr_accessor :org | |
def initialize(ip, len, org) | |
@ip = ip | |
@len = len | |
@org = org | |
end | |
# Returns -1, 0, or 1, if other_ip is, respectively, less than, equal to, or | |
# larger than the item's IP range | |
def compare_ip(other_ip) | |
if other_ip < ip | |
return -1 | |
elsif other_ip - ip < len | |
return 0 | |
end | |
return 1 | |
end | |
end | |
# returns 32bit number corresponding to the IP given as (a, b, c, d) | |
def get_ipnum(a, b, c, d) | |
a << 24 | b << 16 | c << 8 | d | |
end | |
# returns an org name corresponding to the ip given as (a, b, c, d), or nil if | |
# such org does not exist | |
def get_org(db, a, b, c, d) | |
req_ip = get_ipnum(a, b, c, d) | |
# lower and upper indices, both are inclusive | |
l = 0 | |
h = db.length - 1 | |
# loop until we find a needed ip item, or figure that the item does not exist | |
while l <= h do | |
idx = l + (h - l) / 2 | |
case db[idx].compare_ip req_ip | |
when -1 | |
h = idx - 1 | |
when 1 | |
l = idx + 1 | |
else | |
# found an item | |
return db[idx].org | |
end | |
end | |
# requested item does not exist | |
nil | |
end | |
def get_org_p(db, a, b, c, d) | |
p "#{a}.#{b}.#{c}.#{d}: #{get_org(db, a, b, c, d)}" | |
end | |
db = input.map do |a, b, c, d, e, f| | |
IPItem.new(get_ipnum(a, b, c, d), e, f) | |
end | |
# try to find a few orgs | |
get_org_p(db, 0, 255, 255, 255) | |
get_org_p(db, 1, 0, 0, 0) | |
get_org_p(db, 1, 0, 0, 255) | |
get_org_p(db, 1, 0, 1, 0) | |
get_org_p(db, 1, 0, 32, 128) | |
get_org_p(db, 1, 5, 32, 128) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment