【华为机试019】识别有效的IP地址和掩码并进行分类统计

题目描述:

请解析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就是一个非法的掩码)
本题暂时默认 以0开头的IP地址是合法的,比如0.1.1.2,是合法地址

Java实现:

import java.util.*;
public class Main {
     public static void main(String[] args){
        Scanner sc=new Scanner(System.in);
        int isA=0;
        int isB=0;
        int isC=0;
        int isD=0;
        int isE=0;
        int isEroor=0;
        int isPrivate=0;
         
        while(sc.hasNextLine()){
            String str=sc.nextLine();
            String[] ips=str.split("~");
             
            //判断掩码是否合法
            boolean isMask=false;
            String[] maskArr=ips[1].split("\\.");
            String binaryMask="";
            //形成掩码二进制字符串
            for(int i=0;i=1 && ipArr[0]<=126){
                            isA++;
                            if(ipArr[0]==10)
                                isPrivate++;
                        }else if(ipArr[0]>=128 && ipArr[0]<=191){
                            isB++;
                            if(ipArr[0]==172 && (ipArr[1]>=16 && ipArr[1]<=31))
                                 isPrivate++;
                        }else if (ipArr[0]>=192 && ipArr[0]<=223) {
                            isC++;
                            if(ipArr[0]==192 && ipArr[1]==168)
                                 isPrivate++;
                        }else if (ipArr[0]>=224 && ipArr[0]<=239) {
                            isD++;
                        }else if (ipArr[0]>=240 && ipArr[0]<=255) {
                            isE++;
                        }
                    }else{
                        isEroor++;
                    }
                }else {
                    isEroor++;
                }
                 
            }else {
                isEroor++;
            }
        }
        System.out.println(isA+" "+isB+" "+isC+" "+isD+" "+isE+" "+isEroor+" "+isPrivate);
        sc.close();
    }
}

知识点:

  • 在这里判断ip地址是否合法就是判断其是否由四个0到255之间的数字和三个.构成
  • 在正则表达式中“.”表示任意一个字符,因此在用.来分隔字符串时要进行转义\\.
  • 私有IP地址也可以属于某一类

你可能感兴趣的:(华为机试题集Java实现)