xiaoxiaoyuwts的个人空间 https://blog.eetop.cn/?72471 [收藏] [复制] [分享] [RSS]

日志

convert_lpm.py

已有 104 次阅读| 2025-8-16 09:16 |系统分类:其他

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}")



点赞

全部作者的其他最新日志

评论 (0 个评论)

facelist

您需要登录后才可以评论 登录 | 注册

  • 0

    周排名
  • 0

    月排名
  • 0

    总排名
  • 0

    关注
  • 2

    粉丝
  • 0

    好友
  • 0

    获赞
  • 85

    评论
  • 611

    访问数
关闭

站长推荐 上一条 /1 下一条


手机版| 小黑屋| 关于我们| 联系我们| 隐私声明| EETOP 创芯网
( 京ICP备:10050787号 京公网安备:11010502037710 )

GMT+8, 2025-8-18 08:31 , Processed in 0.019345 second(s), 14 queries , Gzip On, Redis On.

eetop公众号 创芯大讲堂 创芯人才网
返回顶部