Skip to content

Instantly share code, notes, and snippets.

@gaoyifan
Created June 11, 2023 08:56
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 gaoyifan/c7d65aae692a2d59a71df99672064d67 to your computer and use it in GitHub Desktop.
Save gaoyifan/c7d65aae692a2d59a71df99672064d67 to your computer and use it in GitHub Desktop.
dhcp option 121 hex format convertor
import ipaddress
def hex_to_cidr(hex_str):
i = 0
while i < len(hex_str):
# The first byte is the mask
mask = int(hex_str[i:i+2], 16)
i += 2
# Calculate how many bytes the subnet will occupy
subnet_bytes = -(-mask // 8)
subnet = '.'.join(str(int(hex_str[i+j*2:i+(j+1)*2], 16)) for j in range(subnet_bytes))
subnet += ''.join('.0' for _ in range(4-subnet_bytes))
i += subnet_bytes * 2
# The next four bytes are the router
router = '.'.join(str(int(hex_str[i+j*2:i+(j+1)*2], 16)) for j in range(4))
i += 8
print(f'{subnet}/{mask}\t{router}')
hex_to_cidr('0FC612C0A801FD175B69C0C0A801FD165B6C04C0A801FD155B6C08C0A801FD155B6C10C0A801FD165B6C38C0A801FD145FA140C0A801FD14959AA0C0A801FD18B94C97C0A801FD')
def cidr_to_hex(cidrs):
hex_str = ''
for cidr, router in cidrs:
# The first byte is the mask
mask = int(cidr.split('/')[1])
hex_str += '{:02X}'.format(mask)
# The next bytes are the subnet
subnet = cidr.split('/')[0]
subnet_bytes = [int(part) for part in subnet.split('.')]
for i in range(-(-mask // 8)):
hex_str += '{:02X}'.format(subnet_bytes[i])
# The next four bytes are the router
router_bytes = [int(part) for part in router.split('.')]
for byte in router_bytes:
hex_str += '{:02X}'.format(byte)
return hex_str
print(cidr_to_hex([
('198.18.0.0/15', ' 192.168.1.253'),
('192.168.93.0/24', ' 192.168.1.253'),
('91.105.192.0/23', ' 192.168.1.253'),
('91.108.4.0/22', ' 192.168.1.253'),
('91.108.8.0/21', ' 192.168.1.253'),
('91.108.16.0/21', ' 192.168.1.253'),
('91.108.56.0/22', ' 192.168.1.253'),
('95.161.64.0/20', ' 192.168.1.253'),
('149.154.160.0/20', ' 192.168.1.253'),
('185.76.151.0/24', ' 192.168.1.253'),
]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment