Convert IPv4 CIDR to IP + subnet mask in python

Question:

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.

Asked By: karoks

||

Answers:

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)
Answered By: Olvin Roght
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.