Classless Inter-Domain Routing (CIDR) (無類別域間路由) 是一個 IP 區間的表示方式,主要寫法如下:
- CIDR 表示方式與 subnet 展開
- 192.0.2.1/32 = 192.0.2.1
- 192.0.2.0/24 = 192.0.2.0 ~ 192.0.2.255
- 192.0.2.0/25 = 192.0.2.0 ~ 192.0.2.127
- 192.0.2.128/25 = 192.0.2.128 ~ 192.0.2.255
使用 Python 要將 CIDR 展開要怎麼做呢?
Python 將 IPv4 CIDR subnet IP 展開
想要將 IPv4 的 CIDR subnet IP範圍展開,可以使用:ipaddress — IPv4/IPv6 manipulation library
Python 使用 ipaddress 的幾個常用的作法
- import ipaddress
- list(ipaddress.ip_network('192.0.2.0/24').subnets())
- [IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/25')]
- str(ipaddress.IPv4Address('192.168.0.1'))
- '192.168.0.1'
- int(ipaddress.IPv4Address('192.168.0.1')) # IP 轉 int
- 3232235521
- str(ipaddress.IPv6Address('::1')) # IPv6
- '::1'
- int(ipaddress.IPv6Address('::1'))
- 1
- IPv4Address('127.0.0.2') + 3 # IP 加減
- IPv4Address('127.0.0.5')
- IPv4Address('127.0.0.2') - 3 # IP 加減
- IPv4Address('126.255.255.255')
- IPv4Address('255.255.255.255') + 1 # 嘗試爆表會發生的錯誤
- ipaddress.AddressValueError: 4294967296 (>= 232) is not permitted as an IPv4 address
Python 使用 ipaddress 列出 IP Range 的範例
from ipaddress import IPv4Network for ip in (ipaddreess.IPv4Network('192.0.2.0/24')): print(ip) # 192.0.2.0 ~ 192.0.2.255