Press "Enter" to skip to content

使用python判断IP段可用IP及数量

使用python判断IP段可用IP及数量, 很简单.几个命令就可以(本文基于python3).

>>> import ipaddress
>>> bool(ipaddress.ip_address('172.21.97.12') in ipaddress.ip_network('172.16.0.0/12'))
True
>>>
>>> for ip in ipaddress.ip_network('192.168.0.0/28'):
...     print(ip)
...
192.168.0.0
192.168.0.1
192.168.0.2
192.168.0.3
192.168.0.4
192.168.0.5
192.168.0.6
192.168.0.7
192.168.0.8
192.168.0.9
192.168.0.10
192.168.0.11
192.168.0.12
192.168.0.13
192.168.0.14
192.168.0.15
>>>
>>> ipaddress.ip_network('192.168.0.0/28').num_addresses
16

批量计算

$ cat 2
172.16.128.0/18
172.16.32.0/20
172.16.64.0/19
172.19.192.0/19
172.16.240.0/21
172.16.48.0/20
172.16.192.0/19
172.19.160.0/19
172.19.64.0/18
172.16.24.0/21
172.16.96.0/19
172.19.128.0/19


$ python3
>>> import ipaddress
>>> with open("./2", "r") as f:
...     for i in f.readlines():
...         print(ipaddress.ip_network(i.rstrip()).num_addresses)
...
16384
4096
8192
8192
2048
4096
8192
8192
16384
2048
8192
8192

 

3 Comments

  1. Anonymous 2021-03-06

    10年了

    • bear 2021-03-30

      是啊, 难得你还记得这个小博客. 我也从一个孩子成长为了一个中年男人. 岁月如梭.

Leave a Reply

Your email address will not be published. Required fields are marked *