/*
*copyright(c) 2014,烟台大学计算机学院
*All rights reserved
*文件名称:test.cpp
*作者:谭泽纯
*版本:v6.0
*
*问题描述: 在互联网中使用的IP地址占4字节,可以用四段法表示,每段值的范围为0-255,中间用“.”隔开,例如202.194.116.97。其实,也可 以看看一个有4字节的无符号整型值3401741409。
现设计一个IP地址类,用于保存IP地址,并实施在IP地址上的一些操作。
*输入描述:无
*程序输出:、答案
*/
#include<iostream>
using namespace std;
class IP
{
private:
union
{
struct
{
unsigned char seg0;
unsigned char seg1;
unsigned char seg2;
unsigned char seg3;
};
unsigned int address;
};
public:
IP(int =0,int=0,int=0,int=0);
void showIP();
bool sameSubnet(const IP &ip, const IP &mark);
char whatKind();
};
IP::IP(int a,int b,int c,int d)
{
seg0=a;
seg1=b;
seg2=c;
seg3=d;
}
//////////////////////借鉴
bool IP::sameSubnet(const IP &ip, const IP &mark)
{
unsigned int i1, i2;
i1=address&mark.address;
i2=ip.address&mark.address;
return (i1==i2);
}
///////////////////////////
void IP:: showIP()
{
int a=seg0;
int b=seg1;
int c=seg2;
int d=seg3;
cout<<a<<"."<<b<<"."<<c<<"."<<d<<endl;
}
char IP ::whatKind()
{
if(seg0<128)
return 'A';
else if(seg0<192)
return 'B';
else if(seg0<224)
return 'C';
else if(seg0<240)
return 'D';
else
return 'E';
}
int main()
{
IP ip1(202,194,116,97),ip2(202,194,119,102),mark(255,255,248,0);
cout<<"ip1:";
ip1.showIP();
cout<<"ip2:";
ip2.showIP();
if(ip1.sameSubnet(ip2,mark))
cout<<"两个IP在同一子网"<<endl;
else
cout<<"两个IP不在同一子网"<<endl;
cout<<"ip1属于"<<ip1.whatKind()<<"类网络"<<endl;
}