How can I generate all possible IPs from a CIDR li

2019-09-05 07:30发布

问题:

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?

回答1:

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



回答2:

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()


回答3:

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)