#include <stdio.h> int valid(int a) { if (a >= 0 && a <= 255) { return 1; } return 0; } int validip(int a, int b, int c, int d) { if (valid(a) && valid(b) && valid(c) && valid(d) ) { return 1; } return 0; } int main() { int s1, s2, s3, s4; while(scanf("%d.%d.%d.%d", &s1, &s2, &s3, &s4) != EOF) { int ip1_1, ip1_2, ip1_3, ip1_4, ip2_1, ip2_2, ip2_3, ip2_4; scanf("%d.%d.%d.%d", &ip1_1, &ip1_2, &ip1_3, &ip1_4); scanf("%d.%d.%d.%d", &ip2_1, &ip2_2, &ip2_3, &ip2_4); if (!validip(ip1_1, ip1_2, ip1_3, ip1_4)) { printf("1\n"); continue; } else if (!validip(ip2_1, ip2_2, ip2_3, ip2_4)) { printf("1\n"); continue; } else if (!validip(s1, s2, s3, s4)) { printf("1\n"); continue; } // 还需要判断是否前缀全都是1 unsigned int sub = 0; sub = (s1 << 24) + (s2 << 16) + (s3 << 8) + s4; int flag = 1; int notvalid = 0; for (int i = 31; i >= 0; i--) { // printf("the i is %d and the (sub >> i) & 1 is %d\n", i , (sub >> i) & 1); if (!((sub >> i) & 1)) { // printf("the %d i is 0\n", i); flag = 0; } if (flag == 0) { if ((sub >> i) & 1) { // printf("the %d i is 1\n", i); notvalid = 1; } } } if (notvalid) { printf("1\n"); continue; } // 如果ip地址和子网掩码都合法,我们对ip地址进行与运算 unsigned int ip1 = (ip1_1 << 24) + (ip1_2 << 16) + (ip1_3 << 8) + ip1_4; unsigned int ip2 = (ip2_1 << 24) + (ip2_2 << 16) + (ip2_3 << 8) + ip2_4; if((ip1 & sub) == (ip2 & sub)) { printf("0\n"); continue; } printf("2\n"); } }