英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论