#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # 2012 Nico Schottelius (nico-cinv at schottelius.org) # # This file is part of cinv. # # cinv is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # cinv is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with cinv. If not, see . # # import argparse import logging import os.path import os import re log = logging.getLogger(__name__) class Error(Exception): pass class Mac(object): def __init__(self): self.base_dir = "." self.prefix = 0x002000000000 #self.prefix = "{:012x}".format(self._prefix) self.free = self.read_file("mac-free") self.last = self.read_file("mac-last") def read_file(self, filename): fname = os.path.join(self.base_dir, filename) ret = [] try: with open(fname, "r") as fd: ret = fd.readlines() except Exception as e: pass return ret def append_to_file(self, text, filename): fname = os.path.join(self.base_dir, filename) with open(fname, "a+") as fd: fd.write("{}\n".format(text)) @staticmethod def validate_mac(mac): if not re.match(r'([0-9A-F]{2}[-:]){5}[0-9A-F]{2}$', mac, re.I): raise Error("Not a valid mac address: %s" % mac) def free_append(self, mac): if mac in self.free: raise Error("Mac already in free database: %s" % mac) self.append_to_file(mac, "mac-free") self.free = self.read_file("mac-free") @staticmethod def int_to_mac(number): b = number.to_bytes(6, byteorder="big") return ':'.join(format(s, '02x') for s in b) def getnext(self): # if self.free: # return self.free.pop() # if not self.prefix: # raise Error("Cannot generate address without prefix - use prefix-set") if self.last: last_number = int(self.last[0], 16) if last_number == int('0xffffff', 16): raise Error("Exhausted all possible mac addresses - try to free some") next_number = last_number + 1 else: next_number = 0 next_number_string = "{:012x}".format(next_number) next_mac_number = self.prefix + next_number next_mac = self.int_to_mac(next_mac_number) with open(os.path.join(self.base_dir, "mac-last"), "w+") as fd: fd.write("{}\n".format(next_number_string)) return next_mac @classmethod def commandline(cls): pass if __name__ == '__main__': m = Mac() m.commandline() # print(m.free) #print(m.last) print(m.getnext())