IPy模塊是用來處理IPv4和IPv6地址的網絡類工具python
>>> from IPy import IP >>> ip = IP('192.168.1.0/29') >>> ip.len() 8 >>> for x in ip: ... print(x) ... 192.168.1.0 192.168.1.1 192.168.1.2 192.168.1.3 192.168.1.4 192.168.1.5 192.168.1.6 192.168.1.7
>>> IP('10.0.0.0/8').version() 4 #IPv4版本 >>> IP('::1').version() 6 #IPv6版本 >>> from IPy import IP >>> ip = IP('192.168.1.20') >>> ip.reverseNames() #反向解析地址 ['20.1.168.192.in-addr.arpa.'] >>> ip.iptype() 'PRIVATE' #ip類型爲私網類型 >>> IP('4.4.4.4').iptype() 'PUBLIC' #公網類型 >>> IP('4.4.4.4').int() 67372036 #整型 >>> IP('4.4.4.4').strHex() '0x4040404' #十六進制 >>> IP('4.4.4.4').strBin() #二進制 '00000100000001000000010000000100' >>> print(IP(0x4040404)) #將十六進制轉換成IP格式 4.4.4.4
>>> IP('127.0.0.0/8') IP('127.0.0.0/8') >>> IP('127.0.0.0/255.0.0.0') IP('127.0.0.0/8') >>> IP('127.0.0.0-127.255.255.255') IP('127.0.0.0/8') >>> from IPy import IP >>> print(IP('192.168.1.0/255.255.255.0',make_net=True)) 192.168.1.0/24 >>> print(IP('192.168.1.0').make_net('255.255.255.0')) 192.168.1.0/24 >>>
輸出格式介紹:網絡
wantprefixlen == 0 / None don't return anything 1.2.3.0 wantprefixlen == 1 /prefix 1.2.3.0/24 wantprefixlen == 2 /netmask 1.2.3.0/255.255.255.0 wantprefixlen == 3 -lastip 1.2.3.0-1.2.3.255
使用strNormal方法指定不一樣wantprefixlen參數來定製輸出不一樣類型的網段: ide
>>> IP('192.168.1.0/24').strNormal() '192.168.1.0/24' >>> IP('192.168.1.0/24').strNormal(0) '192.168.1.0' >>> IP('192.168.1.0/24').strNormal(1) '192.168.1.0/24' >>> IP('192.168.1.0/24').strNormal(2) '192.168.1.0/255.255.255.0' >>> IP('192.168.1.0/24').strNormal(3) '192.168.1.0-192.168.1.255'
一般用來比較兩個網段是否存在重疊。工具
1.判斷IP地址和網段是否包含在另外一個網段中..net
>>> '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
2.判斷兩個網段是否存在重疊。使用overlaps方法。code
>>> IP('192.168.0.0/23').overlaps('192.168.1.0/24') 1 #1表明存在重疊 >>> IP('192.168.0.0/23').overlaps('192.168.2.0') 0 #0表明不存在重疊
附上簡單的Python程序:根據輸入的IP或子網返回網絡、 掩碼、 廣播、反向解析、子網數、 IP類型等信息。orm
#!/usr/bin/python #--*-- coding:utf-8 --*-- #filename:show_ip.py #author:dianel #2018.3.26 17:20:23 from IPy import IP def main(): ip_s = raw_input("Please enter IP:") ip = IP(ip_s) if ip.len() > 1: print('net is: %s' %ip.net()) print('netmask: %s' %ip.netmask()) print('broadcast: %s' %ip.broadcast()) print('reverse address: %s' %ip.reverseNames()[0]) print('subnet: %s' %len(ip)) else: print('reverses address: %s' %ip.reverseNames()[0]) print('version: %s' %ip.version()) print('iptype: %s' %ip.iptype()) print('hexadecimal: %s' %ip.strHex()) if __name__ == '__main__': main()