首页 > 代码库 > python ipaddress模块使用
python ipaddress模块使用
# -*- coding:utf-8 -*- import ipaddress n1 = ipaddress.ip_network(‘192.0.2.0/28‘) n2 = ipaddress.ip_network(‘192.0.2.1/32‘) a = list(n1.address_exclude(n2)) print(a) for i in a: print(i) # 将n2从n1中剔除 b = list(ipaddress.ip_network(‘192.168.0.0/29‘).hosts()) print(b) for i in b: print(i) # 打印主机地址 c = list(ipaddress.ip_network(‘192.168.0.0/22‘).subnets(new_prefix=24)) print(c) for i in c: print(i) # 以24位掩码拆分‘192.168.0.0/22‘ d = list(ipaddress.ip_network(‘192.0.2.0/24‘).supernet(new_prefix=20)) print(d) print(ipaddress.ip_network(‘192.0.2.0/24‘).supernet(new_prefix=20)) for addr in ipaddress.IPv4Network(‘192.168.2.0/28‘): print(addr) # 打印‘192.168.2.0/28‘中的ip地址,注意和上面主机地址的区别 interface = ipaddress.IPv4Interface(‘192.168.1.1/23‘) print(interface.ip) # 打印ip地址 print(interface.network) # 打印所属网段 print(interface.with_netmask) # 与网络的接口的字符串表示作为网络掩码 print(interface.with_prefixlen) # 带有掩码的接口的字符串表示形式,以前缀符号表示。 print(ipaddress.ip_address(3221225985)) # 转换为ip地址 print(ipaddress.v4_int_to_packed(3221225985)) # 转换为字节 print(ipaddress.IPv4Address(3221225985)) # 转换为ip地址 print(ipaddress.IPv4Address(b‘\xc0\x00\x02\x01‘)) # 转换为ip地址 d = [ipaddr for ipaddr in ipaddress.summarize_address_range( ipaddress.IPv4Address(‘192.168.1.0‘), ipaddress.IPv4Address(‘192.168.1.25‘) )] for i in d: print(i) # Network objects can be iterated to list all the addresses belonging to the network. e = [ipaddr for ipaddr in ipaddress.collapse_addresses([ ipaddress.IPv4Network(‘192.168.1.0/31‘), ipaddress.IPv4Network(‘192.168.1.2/31‘), ipaddress.IPv4Network(‘192.168.1.4/30‘)] )] for i in e: print(i) # 将以上三个网段进行合并 print(ipaddress.ip_network(‘192.0.2.1/32‘).compare_networks(ipaddress.ip_network(‘192.0.2.2/32‘))) # 结果为-1 print(ipaddress.ip_network(‘192.0.2.1/32‘).compare_networks(ipaddress.ip_network(‘192.0.2.0/32‘))) # 结果为1 print(ipaddress.ip_network(‘192.0.2.1/32‘).compare_networks(ipaddress.ip_network(‘192.0.2.1/32‘))) # 结果为0 print(ipaddress.IPv4Address(‘127.0.0.2‘) > ipaddress.IPv4Address(‘127.0.0.1‘)) print(ipaddress.IPv4Address(‘127.0.0.2‘) == ipaddress.IPv4Address(‘127.0.0.1‘)) print(ipaddress.IPv4Address(‘127.0.0.2‘) != ipaddress.IPv4Address(‘127.0.0.1‘)) # 比较IP地址 # 实例一:合并IP地址 with open("IP.txt",‘r‘,encoding=‘utf-8‘) as f: allip = f.readlines() ip = [ipaddress.IPv4Network(net.strip(‘\n‘)) for net in allip] ip2 = [addr for addr in ipaddress.collapse_addresses(ip)] for i in ip2: print(i) # 实例二:剔除IP地址(把n2中的ip地址从n1中剔除) n1 = [ipaddress.ip_network(‘192.0.2.0/28‘),ipaddress.ip_network(‘192.1.2.0/28‘)] n2 = [ipaddress.ip_network(‘192.1.2.1/32‘),ipaddress.ip_network(‘192.0.2.4/32‘)] y = [] for i in n1: for x in n2: try: y = list(i.address_exclude(x)) except Exception: pass for z in y: print(z)
本文出自 “baby神” 博客,请务必保留此出处http://babyshen.blog.51cto.com/8405584/1870014
python ipaddress模块使用
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。