| |
import re
import ipaddress
def process_line(line):
has_default_cidr = "0.0.0.0/0" in line
def replace_cidr(match):
cidr = match.group(0)
if cidr == "0.0.0.0/0":
return "::/0"
try:
net = ipaddress.IPv4Network(cidr, strict=False)
net_int = int.from_bytes(net.network_address.packed, byteorder='big')
hex_str = f"{net_int:08x}"
part1 = hex_str[:4]
part2 = hex_str[4:]
new_prefix = 96 + net.prefixlen
return f"::{part1}:{part2}/{new_prefix}"
except Exception as e:
print(f"failed [{cidr}]:{e}")
return cidr
ipv4_pattern = r"\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/(?:3[0-2]|[12]?[0-9])\b"
line_after_cidr = re.sub(ipv4_pattern, replace_cidr, line)
if has_default_cidr:
line_after_cidr = line_after_cidr.replace("#32", "#128")
return line_after_cidr
def process_file(input_path, output_path):
with open(input_path, 'r', encoding='utf-8') as f_in, \
open(output_path, 'w', encoding='utf-8') as f_out:
for line in f_in:
processed_line = process_line(line)
f_out.write(processed_line)
if __name__ == "__main__":
input_file = "ipv4.lpm"
output_file = "v4tov6.lpm"
process_file(input_file, output_file)
print(f"Finished,pls see {output_file}")