求最小子网地址(IP Networks)

来源:互联网 发布:微信发淘宝优惠券软件 编辑:程序博客网 时间:2024/06/06 16:32

给定IPv4的网络地址及其子网掩码,化为32位二进制并按位与,可得到子网IP地址范围。现在的问题是,输入3个IP地址,求出包含它们的最小子网地址。例如,网络地址分别为194.85.160.177(11000000|01010101|10100000|10110001)、194.85.160.178(11000000|01010101|10100000|10110010)和194.85.160.182(11000000|01010101|10100000|10110110),那么包含它们的最小网络地址为194.85.160.176(11000000|01010101|10100000|10110000),子网掩码为255.255.255.248(11111111|11111111|11111111|11111000)。

#include <iostream>#include <cstring>#include <cstdio>using namespace std;const int maxn = 32 + 3;bool address1[maxn], address2[maxn], address3[maxn];bool MinNet[maxn];void TransToBinary(int a, int b, int c, int d, bool addr[]) {int pos = 8;while (a) {addr[--pos] = a % 2;a /= 2;}pos = 16;while (b) {addr[--pos] = b % 2;b /= 2;}pos = 24;while (c) {addr[--pos] = c % 2;c /= 2;}pos = 32;while (d) {addr[--pos] = d % 2;d /= 2;}/*for (int i = 0; i < 32; i++) {if(i%8==0) cout << " ";cout << addr[i];}cout << endl;*/}int FindMinNet() {for (int i = 0; i < 32; i++)if (address1[i] == address2[i] && address1[i] == address3[i] && address2[i] == address3[i])if (!(address1[i+1] == address2[i+1] && address1[i+1] == address3[i+1] && address2[i+1] == address3[i+1]))return i;return 31;}void TransToDecimal(int &a, int &b, int &c, int &d) {a = b = c = d = 0;int start = 32, x = 1;while (x < 256) {d += x * MinNet[--start];x *= 2;}x = 1;while (x < 256) {c += x * MinNet[--start];x *= 2;}x = 1;while (x < 256) {b += x * MinNet[--start];x *= 2;}x = 1;while (x < 256) {a += x * MinNet[--start];x *= 2;}}int main () {int a, b, c, d;while (scanf("%d.%d.%d.%d", &a, &b, &c, &d) != EOF) {memset(address1, 0, sizeof(address1));memset(address2, 0, sizeof(address2));memset(address3, 0, sizeof(address3));TransToBinary(a, b, c, d, address1);scanf("%d.%d.%d.%d", &a, &b, &c, &d);TransToBinary(a, b, c, d, address2);scanf("%d.%d.%d.%d", &a, &b, &c, &d);TransToBinary(a, b, c, d, address3);int pos = FindMinNet();//cout << pos << endl;memcpy(MinNet, address1, sizeof(MinNet));for (int i = pos + 1; i < 32; i++)MinNet[i] = 0;TransToDecimal(a, b, c, d);cout << a << "." << b << "." << c <<"." << d << endl;}return 0;}


0 0
原创粉丝点击