Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Mapping Subnets to VLAN IDs
# attribution of hash goes to Dr. Mange
# (upper_bound-max_projects) / max_efforts
import argparse
import ipaddress
max_projects = 254
max_efforts = 14
lower_bound = 254
upper_bound = 4094
def _mange_hash(project, effort):
if int(effort) == 0:
return project
else:
return (project * (max_efforts + 1) + effort) % (upper_bound - lower_bound) + lower_bound
def _mange_inverse_hash(identifier):
project = ((identifier - lower_bound) // (max_efforts + 1))
effort = ((identifier - lower_bound) % (max_efforts + 1))
address = "10." + str(project) + "." + str(effort) + ".0"
return address
def _test():
hashmap = {}
for project in list(range(0, max_projects + 1, 1)):
for effort in list(range(0, max_efforts + 1, 1)):
vlan_id = _mange_hash(project, effort)
if vlan_id in hashmap.keys():
print("colision with project: " + str(project) + " and effort: " + str(effort))
else:
hashmap[vlan_id] = [project, effort]
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='A Hash Map of Sub-Networks to VLAN IDs')
parser.add_argument('-a', '--addr', default=None, type=str, help='an address in the form of 10.X.Y.0')
parser.add_argument("-i", '--id', default=None, type=int, help='a VLAN ID in the form of an integer [1-4096]')
parser.add_argument('-t', '--test', default=None, type=bool, help='test with the fixed parameters for collision')
args = parser.parse_args()
if args.addr == args.id == args.test == None:
print("Need and ID or IP.")
exit(1)
if args.addr:
try:
address = ipaddress.ip_address(args.addr)
if address.is_private:
project, effort = address.exploded.split('.')[1:3]
if int(effort) <= max_efforts:
print(_mange_hash(int(project), int(effort)))
else:
print("Maximum of x.x.14.0")
else:
print('Not RFC1918 Class A')
except ValueError as error:
print(error)
if args.id:
print(_mange_inverse_hash(args.id))
if args.test:
_test()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.