0

Let's say I have a text file contains a bunch of cidr ip ranges like this:

x.x.x.x/24
x.x.x.x/24
x.x.x.x/23
x.x.x.x/23
x.x.x.x/22
x.x.x.x/22
x.x.x.x/21

and goes on...

How can I convert these cidr notations to all possible ip list in a new text file in Python?

Someone
  • 728
  • 2
  • 12
  • 23
  • possible duplicate of [How can I convert a CIDR list to a IP range list in Python?](http://stackoverflow.com/questions/17641433/how-can-i-convert-a-cidr-list-to-a-ip-range-list-in-python) – brbcoding Jul 14 '13 at 16:56
  • @brbcoding not at all. this question is "generating all possible ips from a cidr list" and that question is "converting a cidr list to a ip range list". "IP range" and "possible ips" are not same thing. They're completely different things. IP range is like "x.x.x.x-y.y.y.y" but possible ip list is every single ip generated from notation. – Someone Jul 14 '13 at 17:02

3 Answers3

1

You can use netaddr for this. The code below will create a file on your disk and fill it with every ip address in the requested block:

from netaddr import *

f = open("everyip.txt", "w")
ip = IPNetwork('10.0.0.0/8')

for addr in ip:
    f.write(str(addr) + '\n')

f.close()
eyeareque
  • 131
  • 1
  • 3
0

based off How can I generate all possible IPs from a list of ip ranges in Python?

import struct, socket
def ips(start, end):
    start = struct.unpack('>I', socket.inet_aton(start))[0]
    end = struct.unpack('>I', socket.inet_aton(end))[0]
    return [socket.inet_ntoa(struct.pack('>I', i)) for i in range(start, end)]

# ip/CIDR
ip = '012.123.234.34'
CIDR = 10
i = struct.unpack('>I', socket.inet_aton(ip))[0] # number
# 175893026
start = (i >> CIDR) << CIDR # shift right end left to make 0 bits
end = i | ((1 << CIDR) - 1) # or with 11111 to make highest number
start = socket.inet_ntoa(struct.pack('>I', start)) # real ip address
end = socket.inet_ntoa(struct.pack('>I', end))
ips(start, end) 
Community
  • 1
  • 1
User
  • 14,131
  • 2
  • 40
  • 59
  • I'm afraid you mistake the CIDR for number of host bits. Your code gives a wrong output. – jfly May 18 '17 at 09:23
  • If I mistake it, how can I improve? Would you like to edit the code, so it works? Should it be `CIDR = 32 - 10`? – User May 18 '17 at 11:01
  • yes, you can try it with `192.168.1.1/24` to verify it. – jfly May 18 '17 at 13:50
0

If you don't need the satisfaction of writing your script from scratch, you could use the python cidrize package.

blackappy
  • 625
  • 7
  • 11