Skip to content

Instantly share code, notes, and snippets.

@Matir
Created September 23, 2018 00:50
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 Matir/e7c3798b40649023a39465133e490e1e to your computer and use it in GitHub Desktop.
Save Matir/e7c3798b40649023a39465133e490e1e to your computer and use it in GitHub Desktop.
Compute strings for DHCP Option 121, Classless Routes
import ipaddress
import math
import sys
def pack_address(addr):
"""Pack an IPv4 Address into colon-delimited format."""
return ':'.join('{:02x}'.format(c) for c in addr.packed)
def pack_subnet(subnet):
"""Pack the subnet."""
sig = math.ceil(subnet.prefixlen / 8)
packed_sig = ':'.join(
'{:02x}'.format(c) for c in subnet.network_address.packed[:sig])
return '{:02x}:{}'.format(subnet.prefixlen, packed_sig)
def parse_pair(subnet, router):
"""Parse a pair into a DHCP route."""
subnet = ipaddress.ip_network(subnet)
router = ipaddress.ip_address(router)
return pack_subnet(subnet) + ':' + pack_address(router)
def main(argv):
pairs = argv[1:]
assert(len(pairs) > 1)
assert(len(pairs) % 2 == 0)
packed = [
parse_pair(pairs[i], pairs[i+1]) for i in range(0, len(pairs), 2)]
print(':'.join(packed))
if __name__ == '__main__':
main(sys.argv)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment