Created
September 23, 2018 00:50
-
-
Save Matir/e7c3798b40649023a39465133e490e1e to your computer and use it in GitHub Desktop.
Compute strings for DHCP Option 121, Classless Routes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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