commit 55eb30f5672a61e85f31637a4eb9ce6975c733e8 Author: Radek Pazdera rpazdera@redhat.com Date: Mon Aug 13 12:01:50 2012 +0200
NetUtils: Adding AddressPool class
This commit introduces AddressPool class (and its two children - MacPool and IpPool). This class can be used to generate (and keep a track of) different types of network addresses within a defined range.
Signed-off-by: Radek Pazdera rpazdera@redhat.com
Common/NetUtils.py | 53 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 files changed, 53 insertions(+), 0 deletions(-) --- diff --git a/Common/NetUtils.py b/Common/NetUtils.py index 42ee6f0..8594a23 100644 --- a/Common/NetUtils.py +++ b/Common/NetUtils.py @@ -53,3 +53,56 @@ def get_corespond_local_ip(query_ip): if ip is None: return ip return ip.group(1) + +class AddressPool: + def __init__(self, start, end): + self._next = self._addr_to_byte_string(start) + self._final = self._addr_to_byte_string(end) + + def _inc_byte_string(self, byte_string): + if len(byte_string): + byte_string[-1] += 1 + if byte_string[-1] > 255: + del byte_string[-1] + self._inc_byte_string(byte_string) + byte_string.append(0) + + def _addr_to_byte_string(self, addr): + pass + + def _byte_string_to_addr(self, byte_string): + pass + + def get_addr(self): + if self._next > self._final: + msg = "Pool exhausted, no free addresses available" + raise Exception(msg) + + addr_str = self._byte_string_to_addr(self._next) + self._inc_byte_string(self._next) + + return addr_str + +class MacPool(AddressPool): + def _addr_to_byte_string(self, addr): + bs = [int(byte, 16) for byte in addr.split(":")] + + if len(bs) != 6: + raise Exception("Malformed MAC address") + + return bs + + def _byte_string_to_addr(self, byte_string): + return ':'.join(map(lambda x: "%02x" % x, byte_string)) + +class IpPool(AddressPool): + def _addr_to_byte_string(self, addr): + bs = [int(byte) for byte in addr.split(".")] + + if len(bs) != 4: + raise Exception("Malformed IP address") + + return bs + + def _byte_string_to_addr(self, byte_string): + return '.'.join(map(str, byte_string))
lnst-developers@lists.fedorahosted.org