Created
December 27, 2024 05:40
-
-
Save rinsuki/94fe3418fcb13aab75497417851ef83b to your computer and use it in GitHub Desktop.
This file contains hidden or 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 re | |
def convert_ipv6_netmask_to_prefixlen(addr: str): | |
addr = ipaddress.IPv6Interface(addr) | |
addr = "".join([f"{byte:08b}" for byte in addr.packed]) | |
return len(re.match("^(1*)(0*)$", addr).group(1)) | |
assert convert_ipv6_netmask_to_prefixlen("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff") == 128 | |
assert convert_ipv6_netmask_to_prefixlen("ffff:ffff:ffff:ffff::") == 64 | |
assert convert_ipv6_netmask_to_prefixlen("ffff:ffff::") == 32 | |
assert convert_ipv6_netmask_to_prefixlen("::") == 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment