Last active
December 28, 2015 06:09
-
-
Save Bystroushaak/7454621 to your computer and use it in GitHub Desktop.
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
#! /usr/bin/env python | |
# -*- coding: utf-8 -*- | |
""" | |
http://stackoverflow.com/questions/19960243/how-to-store-ip-address-range-vs-location | |
by Bystroushaak bystrousak@kitakitsune.org | |
""" | |
# | |
# Interpreter version: python 2.7 | |
# This work is licensed under a Creative Commons 3.0 Unported License | |
# (http://creativecommons.org/licenses/by/3.0/). | |
# | |
in_file = """10.1.100.200- 10.1.100.800 x | |
10.1.101.200- 10.1.101.800 Y | |
10.1.102.200- 10.1.102.800 Z""" | |
def ipToIntArray(s): | |
"""Convert string with IP address into array of numbers""" | |
return map(lambda x: int(x), s.split(".")) | |
def parseString(s): | |
""" | |
Parse string in user-defined format into dictionary: | |
--- | |
10.1.100.200- 10.1.100.800 x | |
--- | |
will be parsed into: | |
{ | |
"f_range": [10.1.100.200] | |
"t_range": [10.1.100.800] | |
"name": "x" | |
} | |
Return array of dicts. | |
""" | |
data = [] | |
for line in s.splitlines(): | |
# skip blank lines | |
if line.strip() == "": | |
continue | |
ranges = line.split("-") | |
f_range = ranges[0].strip() | |
# parse "10.1.102.800 Z" -> t_range, name | |
t_range, name = map(lambda x: x.strip(), ranges[1].strip().split()) | |
data.append({ | |
"f_range": ipToIntArray(f_range), | |
"t_range": ipToIntArray(t_range), | |
"name": name | |
}) | |
return data | |
def fitsIntoRange(ip, range_dict): | |
""" | |
Return True if 'ip' fits into given "range_dict". | |
ip -- string or value returned from ipToIntArray() | |
range_dict -- one parsed line from parseString() | |
""" | |
if isinstance(ip, str): | |
ip = ipToIntArray(ip) | |
bigger = all(map(lambda x: x[0] >= x[1], zip(ip, range_dict["f_range"]))) | |
smaller = all(map(lambda x: x[0] <= x[1], zip(ip, range_dict["t_range"]))) | |
return (bigger and smaller) | |
def findFittingNames(ip, s): | |
""" | |
Return array of names in which 'ip' belongs. | |
""" | |
if isinstance(s, str): | |
data = parseString(s) | |
return map(lambda x: x["name"], filter(lambda x: fitsIntoRange(ip, x), data)) | |
if __name__ == '__main__': | |
# example | |
print findFittingNames("10.1.100.202", in_file) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment