题目描述:
请解析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的个数,之间以空格隔开。
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int typeA = 0;
int typeB = 0;
int typeC = 0;
int typD = 0;
int typE = 0;
int error = 0;
int privIp = 0;
while (scanner.hasNext())
{
String str = scanner.nextLine();
String[] strs = str.split("~");
String ip = strs[0];
String maskCode = strs[1];
//判断ip地址或者掩码格式是否错误
if (!isValidFormat(ip) || !isValidFormat(maskCode))
{
error++;
continue;
}
//判断掩码是否错误
if (!isValidMaskCode(maskCode))
{
error++;
continue;
}
//判断ip类别
String firIp = ip.substring(0, ip.indexOf("."));
int firNum = Integer.valueOf(firIp);
if (firNum >= 1 && firNum <= 126)
{
typeA++;
if (firNum == 10)
privIp++;
}
else if (firNum >= 128 && firNum <= 191)
{
typeB++;
}
else if (firNum >= 192 && firNum <= 223)
{
typeC++;
}
else if (firNum >= 224 && firNum <= 239)
{
typD++;
}
else if (firNum >= 240 && firNum <= 255)
{
typE++;
}
//判断私网
String sec = ip.substring(ip.indexOf(".") + 1);
String secIp = sec.substring(0, sec.indexOf("."));
int secNum = Integer.valueOf(secIp);
if (firNum == 172 && secNum >= 16 && secNum <= 31)
privIp++;
else if (firNum == 192 && secNum == 168)
privIp++;
}
System.out.println(typeA + " " + typeB + " " + typeC + " " + typD + " " + typE + " " + error + " " + privIp);
}
public static boolean isValidFormat(String code)
{
if (code == null || code.equals(""))
return false;
String[] codes = code.split("\\.");
if (codes.length != 4)
return false;
int num = 0;
for (String c: codes)
{
if (c == null || c.equals(""))
return false;
num = Integer.valueOf(c);
if (num < 0 || num > 255)
return false;
}
return true;
}
public static boolean isValidMaskCode(String maskCode)
{
String[] codes = maskCode.split("\\.");
StringBuffer sb = new StringBuffer();
int num = 0;
for (String code: codes)
{
num = Integer.valueOf(code);
sb.append(binaryString(num));
}
int firstIndexOf0 = sb.indexOf("0");
int lastIndexOf1 = sb.lastIndexOf("1");
if (firstIndexOf0 < lastIndexOf1)
return false;
return true;
}
public static String binaryString(int num)
{
StringBuffer sb = new StringBuffer();
int flag = 1 << 7;
for (int i = 0; i < 8; i++)
{
int val = (flag & num) == 0 ? 0 : 1;
sb.append(val);
num <<= 1;
}
return sb.toString();
}
}