- Python网络编程简介
- Python网络编程开发环境
- Python Internet协议模块
- Python IP地址
- Python DNS查找
- Python路由
- Python HTTP请求
- Python HTTP响应
- Python HTTP标头
- Python自定义HTTP请求
- Python请求状态代码
- Python HTTP验证
- Python HTTP数据下载
- Python连接重用
- Python网络接口
- Python Socket程序
- Python HTTP客户端
- Python HTTP服务器
- Python构建URL
- Python Web表单提交
- Python数据库和SQL
- Python Telnet
- Python电子邮件
- Python SMTP
- Python POP3
- Python IMAP
- Python SSH
- Python FTP
- Python SFTP
- Python Web服务器
- Python上传数据
- Python代理服务器
- Python列出目录
- Python远程过程调用
Python IP地址
IP地址(Internet协议)是一种基本的网络概念,可在网络中提供地址分配功能。python模块ipaddress
广泛用于验证IP地址并将其分类为IPV4和IPV6类型。它还可以用于比较IP地址值以及用于处理ip地址的IP地址算法。
1. 验证IPV4地址
ip_address
函数验证IPV4地址。如果值的范围超出0到255,则将引发错误。
print (ipaddress.ip_address(u'192.168.0.255')) print (ipaddress.ip_address(u'192.168.0.256'))
当运行上面的程序时,得到以下输出-
192.168.0.255 ValueError: u'192.168.0.256' does not appear to be an IPv4 or IPv6 address
2. 验证IPV6地址
ip_address
函数验证IPV6地址。如果值的范围超出0
到ffff
,则将引发错误。
print (ipaddress.ip_address(u'FFFF:9999:2:FDE:257:0:2FAE:112D')) #invalid IPV6 address print (ipaddress.ip_address(u'FFFF:10000:2:FDE:257:0:2FAE:112D'))
当运行上面的程序时,得到以下输出-
ffff:9999:2:fde:257:0:2fae:112d ValueError: u'FFFF:10000:2:FDE:257:0:2FAE:112D' does not appear to be an IPv4 or IPv6 address
3. 检查IP地址的类型
我们可以提供各种格式的IP地址,并且该模块将能够识别有效格式。它还将指示它是IP地址的类别。
print type(ipaddress.ip_address(u'192.168.0.255')) print type(ipaddress.ip_address(u'2001:db8::')) print ipaddress.ip_address(u'192.168.0.255').reverse_pointer print ipaddress.ip_network(u'192.168.0.0/28')
当运行上面的程序时,得到以下输出-
255.0.168.192.in-addr.arpa 192.168.0.0/28
4. IP地址比较
可以对IP地址进行逻辑比较,以确定它们是否相等。还可以比较一个IP地址的值是否大于另一个IP地址的值。
print (ipaddress.IPv4Address(u'192.168.0.2') > ipaddress.IPv4Address(u'192.168.0.1')) print (ipaddress.IPv4Address(u'192.168.0.2') == ipaddress.IPv4Address(u'192.168.0.1')) print (ipaddress.IPv4Address(u'192.168.0.2') != ipaddress.IPv4Address(u'192.168.0.1'))
当运行上面的程序时,得到以下输出-
True False True
5. IP地址算术
还可以应用算术运算来操纵IP地址。可以在IP地址中添加或减去整数。如果相加后最后一个八位位组的值超过255,则前一个八位位组将递增以容纳该值。如果多余的值不能被任何先前的八位位组吸收,则将引发值错误。
print (ipaddress.IPv4Address(u'192.168.0.2')+1) print (ipaddress.IPv4Address(u'192.168.0.253')-3) # Increases the previous octet by value 1. print (ipaddress.IPv4Address(u'192.168.10.253')+3) # Throws Value error print (ipaddress.IPv4Address(u'255.255.255.255')+1)
当运行上面的程序时,得到以下输出-
192.168.0.3 192.168.0.250 192.168.11.0 AddressValueError: 4294967296 (>= 2**32) is not permitted as an IPv4 address
下一篇:Python DNS查找
扫描二维码
程序员编程王