Skip to content

Instantly share code, notes, and snippets.

@exhuma
Created November 22, 2018 17:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save exhuma/05e811ba388a073febbc7791fd080b82 to your computer and use it in GitHub Desktop.
Save exhuma/05e811ba388a073febbc7791fd080b82 to your computer and use it in GitHub Desktop.
Class to visualise which blocks in a IP range are occupied by networks and hosts
class IPOccupation:
'''
Class to visualise which blocks in a IP range are occupied by networks and hosts
'''
CHARS = {
0: '\u22c5', # sdot
1: '\u2592', # Medium Shade
2: '\u2588' # Full Block
}
def __init__(self, network) -> None:
self.network = network
self.mask = [0] * network.num_addresses
def occupy(self, entries: list) -> None:
for ip in entries:
intf = ip_interface(ip)
if intf not in self.network:
continue
if intf.ip == intf.network.network_address:
# Occupy the whole network
for host in intf.network:
offset = int(host) & int(self.network.hostmask)
self.mask[offset] = 1
else:
# occupy the single host
offset = int(intf.ip) & int(self.network.hostmask)
self.mask[offset] = 2
def __str__(self) -> str:
textify = [self.CHARS.get(x, str(x)) for x in self.mask]
return ''.join(textify)
def chunked(self, size: int = 8):
'''
Split a list into chunks of a give size.
See https://stackoverflow.com/a/22045226/160665
'''
from itertools import islice
iterator = iter(self.mask)
return iter(lambda: list(islice(iterator, size)), [])
def wrapped(self, hosts_per_block: int = 8, blocks_per_row: int = 4) -> str:
rows = [[]]
for block in self.chunked(hosts_per_block):
if len(rows[-1]) % blocks_per_row == 0:
rows.append([])
textify = [self.CHARS.get(x, str(x)) for x in block]
rows[-1].append(''.join(textify))
joined_rows = [
'Network: %s' % self.network,
'Hosts per block: %d' % hosts_per_block,
'Blocks per row: %d' % blocks_per_row,
'Hosts per row: %d' % (hosts_per_block * blocks_per_row),
'Legend: %s=Free, %s=network reserved, %s=host reserved' % (
self.CHARS[0], self.CHARS[1], self.CHARS[2]
)
]
joined_rows.extend([
'\u2502'.join(row) for row in rows
])
return '\n'.join(joined_rows)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment