Skip to content

Instantly share code, notes, and snippets.

@kagesenshi
Created June 5, 2024 13:57
Show Gist options
  • Save kagesenshi/55a1d859aa3383916de65a40e32d290e to your computer and use it in GitHub Desktop.
Save kagesenshi/55a1d859aa3383916de65a40e32d290e to your computer and use it in GitHub Desktop.
Convert network->gateway mapping into DHCP 121 option
# Convert network->gateway mapping into DHCP 121 option
#
# conf.txt:
#
# 10.210.15.0/24 10.210.14.99
# 10.213.0.0/24 10.210.14.98
# 10.214.0.0/24 10.210.14.98
# 192.168.0.0/24 10.210.14.98
# 172.24.0.0/16 10.210.14.98
#
# usage:
# python3 calculate-dhcp-route.py conf.txt
import argparse
import ipaddress
parser = argparse.ArgumentParser()
parser.add_argument('config')
args = parser.parse_args()
result = []
with open(args.config) as f:
for l in f:
i,g = l.strip().split(' ')
net = ipaddress.IPv4Network(i)
gw = ipaddress.IPv4Address(g)
hm = net.hostmask.packed
na = net.network_address.packed
out = []
include = False
for i in range(3,-1,-1):
if hm[i] != 255 or include:
include = True
out.append(na[i])
out.append(net.prefixlen)
out = list(reversed(out))
for i in gw.packed:
out.append(i)
o = ':'.join([format(o, '02x') for o in out])
print(net,gw,'=>', o)
result.append(o)
print('dhcp 121 => ' + ':'.join(result))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment