1.区分IPv4与IPv6
IP('10.0.0.0/8').version //4
IP('::1').version //6
2.ip类常见的方法
>>>from IPy import IP
>>>ip=IP('192.168.1.20')
>>>ip.reverseName() #反向解析地址格式
>>>ip.iptype() #ip类型
>>>IP('8.8.8.8').int() #转换成整形格式
>>>IP('8.8.8.8').strHex() #转换成十六进制
>>>IP('8.8.8.8').strBin() #转换成二进制
>>>print(IP(0x8080808)) #十六转IP格式
3.ip方法支持网络地址的转换
>>>from IPy import IP
>>>print(IP('192.168.1.0').make_net('255.255.255.0'))
>###192.168.1.0/24
>>>print(IP('192.168.1.0/255.255.255.0',make_net=True))
>###192.168.1.0/24
>>>print(IP('192.168.1.0-192.168.1.255',make_net=True))
>###192.168.1.0/24
4.通过strNormal()指定不同的wantprefixlen参数值定制不同输出类型的网段,输出类型为String
>>>IP('192.168.1.0/24').strNormal(0) #wantprefixlen=0,无返回。
>#'192.168.1.0'
>>>IP('192.168.1.0/24').strNormal(1) #wantprifixlen=1,prefix格式。
>#'192.168.1.0/24'
>>>IP('192.168.1.0/24').strNormal(2) #wantprifixlen=2,decimalnetmask格式。
>#'192.168.1.0/255.255.255.0'
>>>IP('192.168.1.0/24').strNormal(3) #wantprifixlen=3,lastIP格式。
>#'192.168.1.0-192.168.1.255'
5.支持类似数值型数据的比较,以帮助IP对象进行比较。
>>>IP('10.0.0.0/24')<IP('12.0.0.0/24')
>#True
判断IP地址和网段是否包含与另一个网段中
>>>'192.168.1.100' in IP('192.168.1.0/24')
>#True
>>>IP('192.168.1.0/24') in IP('192.168.0.0/16')
>#True
判断两个网段是否存在重叠,overlaps()
>>>IP('192.168.0.0/23').overlaps('192.168.1.0/24')
#1 表示存在重叠
>>>IP('192.168.1.0/23').overlaps('192.168.2.0')
#0 表示不存在重叠
demo
根据输入的ip或子网返回网络,掩码,广播,反向解析,子网数,ip类型等信息。
#!/usr/bin/python
from IPy import IP
#接收用户输入,参数为ip地址或网段地址
ip_s=input('Please input an IP or net-range: ')
ips=IP(ip_s)
if len(ips) > 1: #为一个网络地址
#输出网络地址
print('net: %s' % ips.net())
#输出网络掩码地址
print('netmask: %s' % ips.netmask())
#输出网络广播地址
print('broadcast: %s' % ips.broadcast())
#输出地址反向解析
print('reverse address: %s' % ips.reverseNames()[0])
#输出网络子网数
print('subnet: %s' % len(ips))
#输出地址类型
print('iptype: %s' % ips.iptype())
else: #为单个IP地址
#输出IP反向解析
print('reverse address: %s' % ips.reverseNames()[0])
#输出16进制地址
print('hexadecimal: %s' % ips.strHex())
#输出二进制地址
print('binary ip: %s' % ips.strBin())
#输出地址类型
print('iptype: %s' % ips.iptype())