0%

Python使用IPy模块处理IP地址

Class and tools for handling of IPv4 and IPv6 addresses and networks.

IPy官方地址:https://pypi.python.org/pypi/IPy/
使用范围:IPy 0.83 works on Python version 2.6 – 3.4.,详细请查看官方地址。

安装

1
2
3
4
# wget https://pypi.python.org/packages/88/28/79162bfc351a3f1ab44d663ab3f03fb495806fdb592170990a1568ffbf63/IPy-0.83.tar.gz
# tar -xzf IPy-0.83.tar.gz
# cd IPy-0.83
# python setup.py install

简单使用

IPy模块引入IP类型,可以方便的进行网络计算、地址转换等。

ip地址版本:

1
2
3
4
>>> import IPy
>>> ip = IPy.IP('10.2.0.5')
>>> ip.version()
4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
>>> from IPy import IP
>>> ip = IP('10.6.0.0/16')
>>> ip.len()
65536
>>> ip.iptype()
'PRIVATE'
>>> ip.ip
168165376
>>> ip.net()
IP('10.6.0.0')
>>> ip.netmask()
IP('255.255.0.0')
>>> ip.strNetmask()
'255.255.0.0'
>>> ip.strBin()
'00001010000001100000000000000000'
>>> ip.overlaps('10.6.0.1')
1

strNormal方法已多种形式展示网络和掩码。

1
2
3
4
5
6
7
8
9
10
11
12
>>> ip
IP('10.6.0.0/16')
>>> ip.strNormal()
'10.6.0.0/16'
>>> ip.strNormal(0)
'10.6.0.0'
>>> ip.strNormal(1)
'10.6.0.0/16'
>>> ip.strNormal(2)
'10.6.0.0/255.255.0.0'
>>> ip.strNormal(3)
'10.6.0.0-10.6.255.255'

反向解析:

1
2
3
>>> ip = IP('192.168.0.56')
>>> ip.reverseName()
'56.0.168.192.in-addr.arpa.'

网段比较:

1
2
3
4
>>> '192.168.1.2' in IP('192.168.1.0/28')
True
>>> '192.168.1.0/29' in IP('192.168.1.0/28')
True
1
2
3
4
5
6
7
8
9
10
11
# overlaps方法用于判断两个网段是否有交集,取值范围(-1,0 , 1)。
>>> ip1 = IP('192.168.0.0/16')
>>> ip2 = IP('192.168.0.0/24')
>>> ip3 = IP('192.168.1.0/24')
>>>
>>> ip1.overlaps(ip2)
1
>>> ip2.overlaps(ip3)
0
>>> ip3.overlaps(ip1)
-1

用途提点

IPy可以用到哪些场景呢?

所有用户输入IP场景中,判断输入正确性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
[root@blog python]# cat ip_test.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from IPy import IP

while True:
ip = raw_input('Input IP address: (q/Q to quit)')
if ip == 'q' or ip == 'Q': break
try:
ip = IP(ip)
except ValueError:
print('ValueError')
else:
print('You input the IP address %s' % ip)
break
[root@blog python]#
[root@blog python]# ./ip_test.py
Input IP address: (q/Q to quit)192.168.2.1
You input the IP address 192.168.2.1
[root@blog python]# ./ip_test.py
Input IP address: (q/Q to quit)sdlkf
ValueError
Input IP address: (q/Q to quit)192.168.1.0/8
ValueError
Input IP address: (q/Q to quit)192.168.1.0/24
You input the IP address 192.168.1.0/24