排坑,未判断子网掩码如果不足8位需要补足的情况,新代码用例全部通过
比较复杂,需要考虑为None和''情况下的数据转换情况
需要验证ip和mask的合法性
需要识别ip的类型
最大的坑是如果ip是属于忽略的,那么mask即使是错误的,也需要按照忽略取处理
看我的代码会发现主函数中有忽略,在识别ip中又有忽略类型的返回就是一开始没有注意到上面的坑
其中ip使用逻辑判断,mask使用re模块的正则匹配是最简单,利用bin函数转换隔断数字为二进制并且拼接后匹配正则
import re
import sys
def valid_none(value):
if value is None or value == '':
return False
else:
return True
def valid_ip(ip):
sub_ip_list = list(filter(valid_none, [x for x in ip.split('.')]))
sub_ip_list = [int(x) for x in sub_ip_list]
if len(sub_ip_list) != 4:
return False
elif sub_ip_list[0] > 255 or sub_ip_list[0] < 1:
return False
else:
for sub_ip in sub_ip_list[1:]:
if sub_ip > 255 or sub_ip < 0:
return False
return True
def valid_mask(mask):
sub_mask_list = [int(x) for x in mask.split('.')]
if len(sub_mask_list) != 4:
return False
mask_string = ''
for x in sub_mask_list:
bin_ip_str = str(bin(x))[2:]
mask_string += '0'*(8-len(bin_ip_str)) + bin_ip_str
pattern = re.compile('^[1]{1,32}[0]{1,32}$')
if pattern.search(mask_string):
return True
else:
return False
def judge_public_ip_type(ip):
first_ip = int(ip.split('.')[0])
if 1 <= first_ip <= 126:
return 'A'
elif 128 <= first_ip <= 191:
return 'B'
elif 192 <= first_ip <= 223:
return 'C'
elif 224 <= first_ip <= 239:
return 'D'
elif 240 <= first_ip <= 255:
return 'E'
elif first_ip == 0 or first_ip == 127:
return 'IGNORE'
def judge_private_ip_type(ip):
sub_ip_list = [int(x) for x in ip.split('.')]
first_ip, second_ip = sub_ip_list[0], sub_ip_list[1]
if first_ip == 10:
return True
elif first_ip == 172 and 16 <= second_ip <= 31:
return True
elif first_ip == 192 and second_ip == 168:
return True
return False
if __name__ == '__main__':
A, B, C, D, E, ERROR, PRIVATE = 0, 0, 0, 0, 0, 0, 0
ip_mask_list = sys.stdin
for ip_mask in ip_mask_list:
ip, mask = ip_mask.strip().split('~')
if ip.startswith('0.') or ip.startswith('127.'):
pass
elif valid_ip(ip) and valid_mask(mask):
ip_type = judge_public_ip_type(ip)
if ip_type == 'A':
A += 1
elif ip_type == 'B':
B += 1
elif ip_type == 'C':
C += 1
elif ip_type == 'D':
D += 1
elif ip_type == 'E':
E += 1
else:
pass
if judge_private_ip_type(ip):
PRIVATE += 1
else:
ERROR += 1
print(A, B, C, D, E, ERROR, PRIVATE)
```