将IP范围和CIDR转换为十进制地址

2024-04-29 07:52:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文件包含多种格式的多个IP地址。在

以下是文件示例:

31.14.133.39
37.221.172.0/23
46.19.137.0/24
46.19.143.0/24
50.7.78.88/31
5.79.39.4,5.79.39.5
62.73.8.0/23
63.235.155.210
5.39.216.0,5.39.223.255
64.12.118.23
64.12.118.88

有些是CIDR格式,有些是范围,还有一些是单独的IP。在

以下是3种可能的格式:

^{pr2}$

我想把所有的行转换成IP十进制范围。例如,上面列出的三种格式示例如下所示:

1072405458,1072405458
1044973568,1044974079
86497280,86499327

这个文件大约有40万行。在

我可以通过命令行、Perl、Python或PHP来完成。在


Tags: 文件命令行ip示例格式perlphpcidr
1条回答
网友
1楼 · 发布于 2024-04-29 07:52:24

Python将在^{}模块的帮助下为您完成这项工作。在

from netaddr import IPAddress, IPNetwork

with open("your file.txt", "r") as f:

    for line in f:

        if "/" in line:
            ip_network = IPNetwork(line)
            print "{},{}".format(
                ip_network.first,
                ip_network.last
            )
            continue

        if "," in line:
            first_ip, last_ip = line.split(",")
        else:
            first_ip = last_ip = line

        print "{},{}".format(
            int(IPAddress(first_ip)),
            int(IPAddress(last_ip))
        )

使用您的问题中的三个示例输入和三个预期输出,上面的工作与预期一样。在

相关问题 更多 >