from IPy import IP
class NetIp(object):
def __init__(self,ip=''):
self.ip=ip
def check_valid_net(self):
# 判定是否为网段
if not self.ip.__contains__('/'):
return False
return self.check_valid_ip()
def check_valid_ip(self):
try:
# 判定ip是否合法
IP(self.ip)
return True
except Exception as e:
return False
def str_bin(self):
version=IP(self.ip).version()
if version == 4:
# 将ip地址转二进制并保留ip分隔符
# 255.255.255.255 => 11111111.11111111.11111111.11111111
new_str_bin=''
# 无分隔符二进制
str_bin=IP(self.ip).strBin()
for i in range(len(str_bin)):
if (i+1) % 8 == 0:
# 0-8,8-16,16-24,24-32
new_str_bin += str_bin[i-7:i+1]+'.'
new_str_bin = new_str_bin[:-1]
return new_str_bin
else:
return ''
def origin_str_bin(self):
return IP(self.ip).strBin()
def bit_mask(self):
return IP(self.ip).prefixlen()
def net_bit_mask(self):
bit=0
for num in self.ip.split('.'):
str_bin=str(bin(int(num)))[2:].zfill(8)
bin_index=str_bin.find('0')
if bin_index == -1:
bit+=8
else:
bit+=bin_index
break
return bit
def get_net_range(self):
return IP(self.ip)
def get_net(self):
retrun self.get_net_range().net()
def get_net_prefixlen(self):
retrun self.get_net_range().prefixlen()
def get_mask(self):
retrun self.get_net_range().strNetmask()
def __contains__(self,other):
return IP(other.ip) in IP(self.ip)
def __eq__(self,other):
return IP(other.ip)==IP(self.ip)
def __gt__(self,other):
return IP(other.ip)>IP(self.ip)
def __str__(self):
return str(IP(self.ip))
def __sub__(self,other):
cur_ip=IP(self.ip)
other_ip=IP(other.ip)
ip_contains=other.ip in cur_ip
if cur_ip==other_ip:
return []
if ip_contains:
# 统计差集ip
return self.__sub_ip(cur_ip,other_ip)
else:
return self.__sub_ip(other_ip,cur_ip)
def __sub_ip(self,cur_ip,other_ip):
sub_ip=cur_ip-other_ip
sub_range=[]
for s_i in sub_ip:
for ip in s_i:
sub_range.append(ip)
return sub_range
def __len__(self):
return IP(self.ip).len()
IPy中常用方法封装
最新推荐文章于 2022-02-20 19:53:56 发布