将IPv4 CIDR转换为IP + 子网掩码在Python中

huangapple go评论65阅读模式
英文:

Convert IPv4 CIDR to IP + subnet mask in python

问题

I understand your request, and I will provide the translated code portion without further explanations:

首先对于我的措辞感到抱歉我不知道如何适当地解释但我会尽力

我有一列IP地址如下所示

1.1.1.0/25
2.2.2.0/27
3.3.0.0/22

以此类推 每个项目都在txt文件的不同行中

我想要创建另一个列表但不使用/nn表示法我需要将这些转换为子网掩码

比如

1.1.1.0 255.255.255.128
2.2.2.0 255.255.255.224
3.3.0.0 255.255.252.0

在新的txt文件中每个项目占据新行

如果你不知道子网掩码转换那没关系我可以手动创建一个包含键和值的字典但是我在创建枚举现有列表并将其转换为新列表时遇到了问题
英文:

First of all, sorry about my wording. I don't know how to explain properly but I try.

I have list of IP addresses like below.

1.1.1.0/25
2.2.2.0/27
3.3.0.0/22

and goes on like this. (each item is in different row in a txt file)

I want to another create a list but instead of /nn notation, I need to convert these into Subnet Masks.

such as

1.1.1.0 255.255.255.128
2.2.2.0 255.255.255.224
3.3.0.0 255.255.252.0

(to another txt file with each item in new line)

if you dont know subnet mask conversion thats fine, I can create a dictionary manually with keys and values however I am stuck at creating conversion of notations with enumarating existing list and converting into new list.

答案1

得分: 3

你可以简单地使用 ipaddress.ip_network()

from ipaddress import ip_network

with open("in.txt") as i_f, open("out.txt", "w") as o_f:
    for line in i_f:
        network = ip_network(line.rstrip())
        print(network.network_address, network.netmask, file=o_f)
英文:

You can simply use ipaddress.ip_network().

from ipaddress import ip_network

with open("in.txt") as i_f, open("out.txt", "w") as o_f:
    for line in i_f:
        network = ip_network(line.rstrip())
        print(network.network_address, network.netmask, file=o_f)

huangapple
  • 本文由 发表于 2023年3月8日 19:30:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/75672455.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定