Python netaddr CIDR表示转化

功能

http://netaddr.readthedocs.io/en/latest/tutorial_03.html

将CIDR地址与IP范围相互转化
Convert CIDR to IP range or vice versa.

223.80.97.0/24 —>> 223.80.97.0-223.80.97.255
223.80.97.0-223.80.97.255 —>> 223.80.97.0/24

准备

1
pip install netaddr

Demo

部分代码示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from netaddr import *
# CIDR -> IP Range
test_set = IPSet(['223.80.97.0/28'])
ip_list = []
for ip in test_set:
ip_list.apped(ip)
print ip_list[0], ip_list[-1]
# IP Range -> CIDR
iprange = IPRange('223.80.97.0', '223.80.97.15')
iprange.cidrs()