Ipy

PythonのIP処理モジュールIPy



Ip Processing Module Ipy Python

1.インストール

pip install IPy

2.IPアドレスとネットワークセグメントの基本的な処理



>>> IP('10.0.0.1').version() 4 >>> IP('::1').version() 6 >>> ip=IP('192.168.0.0/16') >>> print ip.len() 65536 >>> for x in ip: ... print x 192.168.36.158 192.168.36.159 192.168.36.160 192.168.36.161 192.168.36.162 192.168.36.163 192.168.36.164 192.168.36.165 192.168.36.166 192.168.36.167 192.168.36.168 192.168.36.169 192.168.36.170 192.168.36.171 192.168.36.172 192.168.36.173 192.168.36.174 192.168.36.175 192.168.36.176

3.一般的な使用法

>>> ip = IP('192.168.10.20') >>> ip.reverseNames() ['20.10.168.192.in-addr.arpa.'] >>> ip.iptype() 'PRIVATE' >>> IP('8.8.8.8').iptype() 'PUBLIC' >>> IP('8.8.8.8').int() 134744072 >>> IP('8.8.8.8').strHex() '0x8080808' >>> IP('8.8.8.8').strBin() '00001000000010000000100000001000 >>> print(IP('0x8080808')) 8.8.8.8 >>> 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 >>> 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' The value and meaning of wantprefixlen: wantprefixlen=0, no return, such as 192.168.1.0 wantprefixlen=1, prefix format, such as 192.168.1.0/24 wantprefixlen=2, decimalnetmask format, such as 192.168.1.0/255.255.255.0 wantprefixlen=3, lastIP format, such as 192.168.1.0-192.168.1.2554

4.マルチネットワーク計算方法



1) IP comparison >>> IP('10.9.1.0/24') '10.9.2.0/24') True 2) Whether the IP address and network are included in another network segment >>> IP('10.9.1.0/24') '10.9.2.0/24') True >>> '192.168.2.100' in IP('192.168.2.0/24') True >>> '192.168.1.0/24' in IP('192.168.0.0/24') False >>> '192.168.1.0/24' in IP('192.168.0.0/16') True 3) Determine whether the network overlaps >>> IP('192.168.0.0/23').overlaps('192.168.1.0/24') 1 #Return 1 means there is overlap >>> IP('192.168.1.0/24').overlaps('192.168.2.0/24') 0 #Return 0 means there is no overlap

5. IPyモジュールの使用例:

#!/bin/python # _*_ coding:utf-8 _*_ from IPy import IP ip_s = raw_input('please input an IP or net-range:') ips = IP(ip_s) if len(ips) > 1: print('net:%s' % ips.net()) #Output network address print('netmask:%s' % ips.netmask()) #Output netmask address print('broadcast:%s' % ips.broadcast())#Output network broadcast address print('reverse address:%s' % ips.reverseNames()[0]) #Output address reverse analysis print('subnet:%s' % len(ips)) else: print('reverse address:%s' % ips.reverseNames()[0]) #Output IP reverse address resolution print('hexadecimal:%s' % ips.strHex()) #Output hexadecimal address print('binary ip:%s' % ips.strBin()) #Output binary address print('iptype:%s' % ips.iptype()) #Output address type

公式リファレンスドキュメントhttp://github.com/haypo/python-ipy