Skip to content

Instantly share code, notes, and snippets.

@lewangdev
Last active December 14, 2020 03:09
Show Gist options
  • Save lewangdev/5a28912c81329cabffcf6031ba8d354d to your computer and use it in GitHub Desktop.
Save lewangdev/5a28912c81329cabffcf6031ba8d354d to your computer and use it in GitHub Desktop.
subnet calculator
#!/usr/bin/env python3
import ipaddress
import sys
def get_cidr_ip_info(ip_net):
try:
net = ipaddress.ip_network(ip_net, strict=False)
print('IP版本号 | %s ' % str(net.version))
print('是否是私有地址 | %s ' % str(net.is_private))
print('IP地址总数 | %s ' % str(net.num_addresses))
print('可用IP地址总数 | %s ' % str(len([x for x in net.hosts()])))
print('网络号 | %s ' % str(net.network_address))
print('起始可用IP地址 | %s ' % str([x for x in net.hosts()][0]))
print('最后可用IP地址 | %s ' % str([x for x in net.hosts()][-1]))
print('可用IP地址范围 | %s ' % (str([x for x in net.hosts()][0]) + ' ~ ' + str([x for x in net.hosts()][-1])))
print('掩码地址 | %s ' % str(net.netmask))
print('反掩码地址 | %s ' % str(net.hostmask))
print('广播地址 | %s ' % str(net.broadcast_address))
except ValueError:
print('输入格式有误,请检查!')
if __name__ == '__main__':
#cidr_ip = '192.168.1.1/24'
cidr_ip = sys.argv[1]
get_cidr_ip_info(cidr_ip)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment