您的位置:首页 > 理论基础

IP地址

2016-04-10 13:23 260 查看
问题及代码:

/*
*Copyright (c) 2016,烟台大学计算机学院
*All rights reserved.
*文件名称:main.cpp
*作 者:李磊涛
*完成时间:2016年4月10日
*版 本 号:v1.0
*
*问题描述:简单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)
{
seg3=a;
seg2=b;
seg1=c;
seg0=d;
}
void IP::showIP()
{
cout<<int(seg3)<<"."<<int(seg2)<<"."<<int(seg1)<<"."<<int(seg0)<<endl;
}
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);
}
char IP::whatKind()
{
if(seg3<128)
return 'A';
else if(seg3<192)
return 'B';
else if(seg3<224)
return 'C';
else if(seg3<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;
return 0;
}

运行结果:



知识点总结:

通过该程序,强化了我对类的组合的认识。

学习心得:

目前还是不会写关于是否处于同一子网的算法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ 计算机