1 ip地址的格式:...坦弟,并且值不能超過255护锤,使用正則表達式
String pattern = "^(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}$";
2 掩碼除了要滿足ip地址的格式外,轉(zhuǎn)化為2進制后酿傍,0的后面不能有1
public static boolean maskCheck(String str) {
if (str != null && !str.isEmpty()) {
String s[] = str.split("[.]");
String binary = "";
for (int i = 0; i < s.length; ++i) {
binary = binary + getBinary(s[i]);
}
if (binary.contains("01"))
return false;
else return true;
}
return false;
}
3 判斷兩個ip地址是否屬于同一網(wǎng)絡,比較子網(wǎng)掩碼為1的前幾位是否相同
public class Test {
public static int checkNetSegment(String mask, String ip1, String ip2) {
//驗證ip地址是否合法
if ((ipCheck(mask) && maskCheck(mask)) == false || ipCheck(ip1) == false || ipCheck(ip2) == false)
return 1;
//求出網(wǎng)絡位
String net[] = mask.split("[.]");
int len = getlen(net[0]) + getlen(net[1]) + getlen(net[2]) + getlen(net[3]);
//獲取ip的二進制
String ip1s[] = ip1.split("[.]");
String Ip1 = "";
String Ip2 = "";
String ip2s[] = ip2.split("[.]");
int i = (len % 8 == 0 ? len / 8 : len / 8 + 1);
for (int j = 0; j < i; ++j) {
Ip1 = Ip1 + getBinary(ip1s[j]);
Ip2 = Ip2 + getBinary(ip2s[j]);
}
if (len % 8 != 0) {
return Ip1.substring(0, len).equals(Ip2.substring(0, len)) ? 0 : 2;
} else
return Ip1.equals(Ip2) ? 0 : 2;
}
public static int getlen(String s) {
int n = Integer.parseInt(s);
int m = 0;
if (n == 0) {
return 0;
} else {
while (n / 2 != 0) {
if (n % 2 != 0) {
++m;
}
n = n / 2;
}
return m + 1;
}
}
public static String getBinary(String s) {
String b[] = {"0", "00", "000", "0000", "00000", "000000", "0000000", ""};
int n = Integer.parseInt(s);
String m = "";
if (n == 0)
return "00000000";
while (n / 2 != 0) {
m = n % 2 + m;
n = n / 2;
}
return (m.length() < 7 ? b[6 - m.length()] : "") + "1" + m;
}
public static boolean ipCheck(String str) {
if (str != null && !str.isEmpty()) {
String pattern = "^(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}$";
if (str.matches(pattern))
return true;
return false;
}
return false;
}
public static boolean maskCheck(String str) {
if (str != null && !str.isEmpty()) {
String s[] = str.split("[.]");
String binary = "";
for (int i = 0; i < s.length; ++i) {
binary = binary + getBinary(s[i]);
}
if (binary.contains("01"))
return false;
else return true;
}
return false;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (input.hasNext()) {
String mask = input.next();
String ip1 = input.next();
String ip2 = input.next();
System.out.println(checkNetSegment(mask,ip1,ip2));
}
}
}
- 輸出
1:不滿足格式
2:不在同一個子網(wǎng)
0: 在同一個子網(wǎng)