题解 | #识别有效的IP地址和掩码并进行分类统计#
识别有效的IP地址和掩码并进行分类统计
https://www.nowcoder.com/practice/de538edd6f7e4bc3a5689723a7435682
利用正则表达式匹配有效地IP地址和子网掩码
import re ip_pattern = re.compile( r'(?=(\b))(((\d{1,2})|(1\d{1,2})|(2[0-4]\d)|(25[0-5]))\.){3}((\d{1,2})|(1\d{1,2})|(2[0-4]\d)|(25[0-5]))(?=(\b))') mask_pattern = re.compile(r'^1+0+$') # A、B、C、D、E、错误IP地址或错误掩码、私有IP的个数 cnt = [0, 0, 0, 0, 0, 0, 0] # private = [10, 172, 192] while 1: try: origList = input().split('~') # ['10.70.44.68'. '255.254.255.0'] ipstr, maskcode = origList[0], origList[1] maskList = maskcode.split('.') masks = [str(bin(int(m))) for m in maskList] mask2 = [a[2:].zfill(8) for a in masks] maskstr = ''.join(mask2) if re.match(ip_pattern, ipstr): ipNum = ipstr.split('.') ipOne = int(ipNum[0]) ipTwo = int(ipNum[1]) # 忽略条件 if ipOne == 127 or ipOne == 0: continue # 私有IP ''' 私网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 ''' if re.match(mask_pattern, maskstr): # and re.match(bin_pattern, maskstr): if (1 <= ipOne <= 126): cnt[0] += 1 if ipOne == 10: cnt[-1] += 1 elif (ipOne < 192): cnt[1] += 1 if ipOne == 172 and 16 <= ipTwo <= 31: cnt[-1] += 1 elif ipOne < 224: cnt[2] += 1 if ipOne == 192 and ipTwo == 168: cnt[-1] += 1 elif ipOne < 240: cnt[3] += 1 else: cnt[4] += 1 else: cnt[5] += 1 # 错误的IP或子网掩码 else: cnt[5] += 1 except: break print(' '.join([str(i) for i in cnt]))