描述
请解析IP地址和对应的掩码,进行分类识别。要求按照A/B/C/D/E类地址归类,不合法的地址和掩码单独归类。
所有的IP地址划分为 A,B,C,D,E五类
A类地址从1.0.0.0到126.255.255.255;
B类地址从128.0.0.0到191.255.255.255;
C类地址从192.0.0.0到223.255.255.255;
D类地址从224.0.0.0到239.255.255.255;
E类地址从240.0.0.0到255.255.255.255
私网IP范围是:
从10.0.0.0到10.255.255.255
从172.16.0.0到172.31.255.255
从192.168.0.0到192.168.255.255
子网掩码为二进制下前面是连续的1,然后全是0。(例如:255.255.255.32就是一个非法的掩码)
(注意二进制下全是1或者全是0均为非法子网掩码)
注意:
- 类似于【0...】和【127...】的IP地址不属于上述输入的任意一类,也不属于不合法ip地址,计数时请忽略
- 私有IP地址和A,B,C,D,E类地址是不冲突的
输入描述:
多行字符串。每行一个IP地址和掩码,用~隔开。
请参考帖子https://www.nowcoder.com/discuss/276处理循环输入的问题。
输出描述:
统计A、B、C、D、E、错误IP地址或错误掩码、私有IP的个数,之间以空格隔开。
示例
示例1
输入:
10.70.44.68~255.254.255.0
1.0.0.1~255.0.0.0
192.168.0.2~255.255.255.0
19..0.~255.255.255.0
输出:
1 0 1 0 0 2 1
说明:
10.70.44.68~255.254.255.0的子网掩码非法,19..0.~255.255.255.0的IP地址非法,所以错误IP地址或错误掩码的计数为2;
1.0.0.1~255.0.0.0是无误的A类地址;
192.168.0.2~255.255.255.0是无误的C类地址且是私有IP;
所以最终的结果为1 0 1 0 0 2 1
示例2
输入:
0.201.56.50~255.255.111.255
127.201.56.50~255.255.111.255
输出:
0 0 0 0 0 0 0
说明:
类似于【0.*.*.*】和【127.*.*.*】的IP地址不属于上述输入的任意一类,也不属于不合法ip地址,计数时请忽略
代码
python
import re
a_num = 0
b_num = 0
c_num = 0
d_num = 0
e_num = 0
s_num = 0
err_num = 0
def is_numeric(s):
try:
num = int(s)
if 0 <= num <= 255:
return True
else:
return False
except ValueError:
return False
def belongIp(ip,ym_arr):
global a_num
global b_num
global c_num
global d_num
global e_num
global s_num
ip_arr = [int(x) for x in ip.split(".")]
if (
1 <= ip_arr[0] <= 126
and 0 <= ip_arr[1] <= 255
and 0 <= ip_arr[2] <= 255
and 0 <= ip_arr[3] <= 255
):
a_num += 1
# print(ip, ym_arr)
if ip_arr[0] == 10:
s_num += 1
elif (
128 <= ip_arr[0] <= 191
and 0 <= ip_arr[1] <= 255
and 0 <= ip_arr[2] <= 255
and 0 <= ip_arr[3] <= 255
):
b_num += 1
if ip_arr[0] == 172 and 16 <= ip_arr[1] <= 31:
s_num += 1
elif (
192 <= ip_arr[0] <= 223
and 0 <= ip_arr[1] <= 255
and 0 <= ip_arr[2] <= 255
and 0 <= ip_arr[3] <= 255
):
c_num += 1
if ip_arr[0] == 192 and ip_arr[1] == 168:
s_num += 1
elif (
224 <= ip_arr[0] <= 239
and 0 <= ip_arr[1] <= 255
and 0 <= ip_arr[2] <= 255
and 0 <= ip_arr[3] <= 255
):
d_num += 1
elif (
240 <= ip_arr[0] <= 255
and 0 <= ip_arr[1] <= 255
and 0 <= ip_arr[2] <= 255
and 0 <= ip_arr[3] <= 255
):
e_num += 1
# arr = input().split()
# print(arr)
# for index in range(len(arr)):
while True:
try:
s = input().split("~")
# s = arr[index].split("~")
ip_arr = s[0].split(".")
ip_arr_h = [x for x in ip_arr if is_numeric(x)]
ym_arr = [str(bin(int(v))).replace("0b", "").zfill(8) for v in s[1].split(".")]
isYm = re.match(r"^1+0+$", "".join(ym_arr))
if len(ip_arr_h) == 4 and len(ip_arr) == 4:
if ip_arr_h[0] != '0' and ip_arr_h[0] != '127':
if isYm:
belongIp(s[0],ym_arr)
else:
err_num += 1
else:
err_num += 1
except:
break
print(a_num, b_num, c_num, d_num, e_num, err_num, s_num)