题解 | #识别有效的IP地址和掩码并进行分类统计#

识别有效的IP地址和掩码并进行分类统计

https://www.nowcoder.com/practice/de538edd6f7e4bc3a5689723a7435682

"""
判断IP是哪种类别

"""
def judgeIpClaasification(ip):
    try:
        ip_list=[int(i) for i in ip.split('.')]
    except:
        return 'ErrorIp','drop'
    for i in [1,2,3]:
        if ip_list[i]<=255 and ip_list[i]>=0:
            pass
        else:
            return 'ErrorIp','drop'
    if ip_list[0]==0 or ip_list[0]==127:
        return 'drop','drop'
    elif ip_list[0]<=126 and ip_list[0]>=1:
        if ip_list[0]==10:
            return 'A','PrivateIp'
        else:
            return 'A','drop'
    elif ip_list[0]<=191 and ip_list[0]>=128:
        if ip_list[0]==172 and ip_list[1]>=16 and ip_list[1]<=31:
            return 'B','PrivateIp'
        else:
            return 'B','drop'
    elif ip_list[0]<=223 and ip_list[0]>=192:
        if ip_list[0]==192 and ip_list[1]==168:
            return 'C','PrivateIp'
        else:
            return 'C','drop'
    elif ip_list[0]<=239 and ip_list[0]>=224:
        return 'D','drop'

    elif ip_list[0]<=255 and ip_list[0]>=240:
        return 'E','drop'

"""
子网掩码为二进制下前面是连续的1,然后全是0。(例如:255.255.255.32就是一个非法的掩码)
(注意二进制下全是1或者全是0均为非法子网掩码)
"""
def getBin(s):
    erjinzhi=bin(int(s))[2:]
    if len(erjinzhi)!=8:
        erjinzhi=''.join(['0'*(8-len(erjinzhi)),erjinzhi])
    return erjinzhi

def judgeYanMaClassification(ip):
    ip_list=ip.split('.')
    new_yanma=''
    for i in ip_list:
        new_yanma+=getBin(i)
    #全是0或者1的掩码也是错的
    if len(new_yanma)==new_yanma.count('0') or len(new_yanma)==new_yanma.count('1'):
        return False
    first_0=new_yanma.index('0')
    #确保掩码前半段都是1,后半段都是0.
    if '0' in new_yanma[:first_0]:
        return False
    if '1' in new_yanma[first_0:]:
        return False
    else:
        return True

Count_list={
    'A':0,
    'B':0,
    'C':0,
    'D':0,
    'E':0,
    'ErrorIp':0,
    'PrivateIp':0,
    'drop':0
}
A,B,C,D,E,ErrorIp,PrivateIp=0,0,0,0,0,0,0
try:
    while True:
        s=input()
        first,second=s.split('~')
        #如果ip是0或者127开头的,就不会继续下面的判断了
        first_1=first.split('.')[0]
        if first_1=='0' or first_1=='127':
            pass
        else:
            #如果掩码错了,就不会继续判断了
            yanma_res=judgeYanMaClassification(second)
            if not yanma_res:
                Count_list['ErrorIp']+=1
            else:
                res1,res2=judgeIpClaasification(first)

                Count_list[res1]+=1
                Count_list[res2]+=1

except Exception:
    print('{} {} {} {} {} {} {}'.format(Count_list['A'],Count_list['B'],Count_list['C'],
                                            Count_list['D'],Count_list['E'],Count_list['ErrorIp'],Count_list['PrivateIp']
                                            ))

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务