您的位置:首页 > 其它

华为OJ中级题-识别有效的IP地址和掩码并进行分类统计

2015-12-11 10:40 489 查看
请解析IP地址和对应的掩码,进行分类识别。要求按照A/B/C/D/E类地址归类,不合法的地址和掩码单独归类。

所有的IP地址划分为 A,B,C,D,E五类

A类地址1.0.0.0~126.255.255.255;

B类地址128.0.0.0~191.255.255.255;

C类地址192.0.0.0~223.255.255.255;

D类地址224.0.0.0~239.255.255.255;

E类地址240.0.0.0~255.255.255.255

私网IP范围是:

10.0.0.0~10.255.255.255

172.16.0.0~172.31.255.255

192.168.0.0~192.168.255.255

子网掩码为前面是连续的1,然后全是0

int IP[8] = { 0 };//0-3IP地址,4-7Mask码
int a = 0, b = 0, c = 0, d = 0, e = 0,F=0,G=0;//按照A/B/C/D/E类地址归类,不合法的地址和掩码单独归类,私有地址归类
void funa(string x){
int len = x.length();
string tmp;
int num,ip=0,mask=0;
stringstream ss;
for (int i = 0; i < len; ++i)
{

if (x[i] == '.'||x[i]=='~'){
if (tmp == "")tmp = "999";
ss << tmp;
ss >> num;
//cout << num << " ";
IP[ip++] = num;
ss.clear(); tmp.clear();
}
else{
tmp.push_back(x[i]);
}
}
ss << tmp;
ss >> num;
// cout << num << " ";
IP[ip] = num;
ss.clear(); tmp.clear();
}
void funClass(){
if (IP[0] <= 126)++a;
if (IP[0] >= 128 && IP[0] <= 191)++b;
if (IP[0] >= 192 && IP[0] <= 223)++c;
if (IP[0] >= 240 && IP[0] <= 255)++d;

if (IP[0] == 10)++G;
if ((IP[1]>=16)&&(IP[1] <= 31)&&( IP[0]=172))++G;
if (IP[1] == 168 && IP[0] == 192)++G;
}
bool findIpNMask(int x[]){
bool f = true;
for (int i = 0; i < 4; ++i){
if (IP[i] > 255){ ++F;f=false; break; }
}
for (int i = 4; i < 8; ++i){
if (IP[i] != 255 && IP[i] != 0){ ++F; f = false; break; }
}
return f;
}
void HWoj(string str){
//string str = "192..0.~255.255.255.0";
funa(str);
for (int i = 0; i < 8; ++i){
funa(str);
}
if (findIpNMask(IP)){
funClass();
}
cout << a << " " << b << " " << c << " " << d << " " << F << " " << G;
cout << endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: