子网掩码(25分)
- 问题描述
子网掩码是用来判断任意两台计算机的IP地址是否属于同一子网络的根据。最为简单的理解就是两台计算机各自的IP地址与子网掩码进行AND运算后,如果得出的结果是相同的,则说明这两台计算机是处于同一个子网络上的,可以进行直接的通讯。就这么简单。
请看以下示例:
运算演示之一:
IP地址 192.168.0.1
子网掩码 255.255.255.0
转化为二进制进行运算:
IP地址 11000000.10101000.00000000.00000001
子网掩码 11111111.11111111.11111111.00000000
AND运算:
11000000.10101000.00000000.00000000
转化为十进制后为:
192.168.0.0
运算演示之二:
IP地址 192.168.0.254
子网掩码 255.255.255.0
转化为二进制进行运算:
IP地址 11000000.10101000.00000000.11111110
子网掩码 11111111.11111111.11111111.00000000
AND运算:
11000000.10101000.00000000.00000000
转化为十进制后为:
192.168.0.0
运算演示之三:
IP地址 192.168.0.4
子网掩码 255.255.255.0
转化为二进制进行运算:
IP地址 11000000.10101000.00000000.00000100
子网掩码 11111111.11111111.11111111.00000000
AND运算:
11000000.10101000.00000000.00000000
转化为十进制后为:
192.168.0.0
通过以上对三组计算机IP地址与子网掩码的AND运算后,我们可以看到它运算结果是一样的,均为192.168.0.0,所以计算机就会把这三台计算机视为在同一子网络。
- 输入
输入的第一行是本机IP地址;
第二行是子网掩码;
第三行是一个整数N,表示后面有N个IP地址;
接下来N行:
第1个IP地址
…
…
第N个IP地址
- 输出
计算并输出N个IP地址是否与本机在同一子网内。对于在同一子网的输出“INNER”,对于在不同子网的输出“OUTER”。
- 输入样例
192.168.0.1
255.255.255.0
3
192.168.0.2
192.168.0.254
192.168.1.2
- 输出样例
INNER
INNER
OUTER
#include<bits/stdc++.h>
using namespace std;
string two(int n){ //进行二进制转换
string a = "";
do{
char c = n % 2 + '0';
a += c;
n = n / 2;
}while(n!=0);
if(a.length() < 8){ //不满八位进行补0
for(int i = a.length();i < 8;i++){
a+='0';
}
}
reverse(a.begin(),a.end());
return a;
}
int cmp(string a,string b,string c){ //计算掩码
for(int i = 0;i < 8;i++){
if(b[i] != c[i]){ //进行and运算
c[i] = '0';
}
if(b[i] != a[i]){
a[i] = '0';
}
}
return a == c ? 1 : 0; //比较子码 判断是否在一子网
}
int main(){
int a1,a2,a3,a4;
int b1,b2,b3,b4;
scanf("%d.%d.%d.%d",&a1,&a2,&a3,&a4);
scanf("%d.%d.%d.%d",&b1,&b2,&b3,&b4);
string str1 = two(a1);
string str2 = two(a2);
string str3 = two(a3);
string str4 = two(a4);
string str5 = two(b1);
string str6 = two(b2);
string str7 = two(b3);
string str8 = two(b4);
int n;
cin>>n;
for(int i = 0;i < n;i++){
int c1,c2,c3,c4;
scanf("%d.%d.%d.%d",&c1,&c2,&c3,&c4);
string cstr1 = two(c1);
string cstr2 = two(c2);
string cstr3 = two(c3);
string cstr4 = two(c4);
if(cmp(str1,str5,cstr1)&&cmp(str2,str6,cstr2)&&cmp(str3,str7,cstr3)&&cmp(str4,str8,cstr4)) printf("INNER\n");
else printf("OUTER\n");
}
}