java实现识别有效IP并分类
识别有效的IP地址和掩码并进行分类统计
http://www.nowcoder.com/questionTerminal/de538edd6f7e4bc3a5689723a7435682
字符串分割,暴力判断。。。默默吐槽一下牛客的题目描述,规则不清晰,IP和掩码只要其中一个非法,另一个就不判断了,直接下一组。。给的示例正好有误导作用,试了好几遍才摸清这个规则。。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
private static int a = 0, b = 0, c = 0, d = 0, e = 0, error = 0, privateIp = 0;
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String str = "";
while ((str = reader.readLine()) != null){
final String[] strings = str.split("~");
final String[] ip = strings[0].split("\\.");
final String[] mask = strings[1].split("\\.");
if (checkIp(ip) && checkIp(mask) && checkMask(mask)){
checkIpKind(ip);
}else {
error++;
}
}
System.out.println(a + " " + b + " " + c + " " + d + " " + e + " " + error + " " + privateIp);
reader.close();
}
public static void checkIpKind(String[] ip){
if (ip.length == 4){
int first = Integer.parseInt(ip[0]);
int second = Integer.parseInt(ip[1]);
if (first == 0 || first == 127) return;
// 先判断是不是私有的
if (first == 10 || (first == 172 && second <= 31 && second >= 16)
|| (first == 192 && second == 168)) {
privateIp++;
}
// 判断其他类
if (first >= 1 && first <= 126){
a++;
}else if (first >= 128 && first <= 191){
b++;
}else if (first >= 192 && first <= 223){
c++;
}else if (first >= 224 && first <= 239)
d++;
else if (first >= 240 && first <= 255) e++;
}
}
public static boolean checkIp(String[] ip){
if (ip.length != 4) return false;
for (int i = 0; i < ip.length; i++) {
if (ip[i].equals("")) return false;
int anInt = Integer.parseInt(ip[i]);
if (anInt > 255 || anInt < 0) return false;
}
Long unsinged = ip2Unsinged(ip);
final String binaryString = Long.toBinaryString(unsinged);
if (!binaryString.contains("1") || !binaryString.contains("0")) return false;
return true;
}
public static Long ip2Unsinged(String[] ip){
Long unsinged = 0L;
for (int i = 0; i < ip.length; i++) {
unsinged |= Long.parseLong(ip[i]) << 8 * (ip.length - i - 1);
}
return unsinged;
}
public static boolean checkMask(String[] mask){
if (mask.length != 4) return false;
Long unsinged = ip2Unsinged(mask);
boolean cantZero = true;
while (unsinged != 0){
final long bit = unsinged & 0x01;
if (bit == 0) {
unsinged >>>= 1;
if (!cantZero) return false;
cantZero = true;
continue;
}
unsinged >>>= 1;
cantZero = false;
}
return true;
}
}