识别有效的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,是合法地址


输入描述:

多行字符串。每行一个IP地址和掩码,用~隔开。

输出描述:

统计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


实现代码:

import java.util.Scanner;

public class Main{
	private static int a = 0;
	private static int b = 0;
	private static int c = 0;
	private static int d = 0;
	private static int e = 0;
	private static int error = 0;
	private static int p = 0;

	
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		String str ;
		while(sc.hasNext()){
			str = sc.nextLine();			
			getInfo(str);
		}
		System.out.println(a+" "+b+" "+c+" "+d+" "+e+" "+error+" "+p);
		sc.close();
	}

	public static void getInfo(String str){
		String[] address = new String[2];
		int[] ipInt = new int[4];
		int[] maskInt = new int[4];
		
		address= str.split("~");
		String[] ip = address[0].split("\\.");
		String[] mask = address[1].split("\\.");			
		if(ip.length < 4 || mask.length < 4){
			error++;
			return;
		}
		
		for(int i=0;i<4;i++){
			if("".equals(ip[i]) || "".equals(mask[i]) || " ".equals(ip[i]) || " ".equals(mask[i])){
				error++;
				return;
			}
		}
		
		for(int i=0;i<4;i++){
			ipInt[i] = Integer.parseInt(ip[i]);
			maskInt[i] = Integer.parseInt(mask[i]);
			if(ipInt[i]<0 || ipInt[i]>255 || maskInt[i]<0 || maskInt[i]>255){
				error++;
				return;
			}
		}
		
		if(maskInt[0]==255 && maskInt[1]==255 && maskInt[2]==255 && maskInt[3]==255){
			error++;
			return;
		}
		
		long maskLong = maskInt[0]*(0xffffff+1)+maskInt[1]*(0xffff+1)+maskInt[2]*(0xff+1)+maskInt[3];
		if(((maskLong-1) | maskLong) != 0xffffffff){
			error++;
			return;
		}
		
		if((ipInt[0] == 10)
                || (ipInt[0] == 172 && ipInt[1] >= 16 && ipInt[1] <= 31)
                || (ipInt[0] == 192 && ipInt[1] == 168)){
			p++;
		}
		
		if(ipInt[0] >=1 && ipInt[0] <=126){
			a++;
		}
		if(ipInt[0] >=128 && ipInt[0] <=191){
			b++;
		}
		if(ipInt[0] >=192 && ipInt[0] <=223){
			c++;
		}
		if(ipInt[0] >=224 && ipInt[0] <=239){
			d++;
		}
		if(ipInt[0] >=240 && ipInt[0] <=255){
			e++;
		}		
	}
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值