How can I generate all possible IPs from a CIDR list in Python?

拜拜、爱过 提交于 2019-12-13 07:00: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) 


来源:https://stackoverflow.com/questions/17641433/how-can-i-convert-a-cidr-list-to-a-ip-range-list-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!