IP地址类

来源:互联网 发布:淘宝买家自动评价软件 编辑:程序博客网 时间:2024/06/06 14:11
/* *Copyright(c)2016,LynseyListening *All rights reserced. *文件名称:listening.cpp *作者    :陈旭 *完成日期:2016.5.25 *版本号  :codeblocks 16.01*/#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();    char whatKind();    bool sameSubnet(const IP &ip, const IP &mark);};IP::IP(int s0,int s1,int s2,int s3){    seg3=s0;    seg2=s1;    seg1=s2;    seg0=s3;}void IP::showIP(){    cout<<int(seg3)<<"."<<int(seg2)<<"."<<int(seg1)<<"."<<int(seg0)<<endl;    return;}bool IP::sameSubnet(const IP &ip, const IP &mark){    unsigned int i1, i2;    i1=ip.address&mark.address;//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!    i2=ip.address&mark.address;//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!    return (i1==i2);//先把数字转换成二进制的,然后从低位向高位一一对应,再就是运算了,相当于数学里的真假与并,即1&1=1,1&0=0&1=0&0=0  百度-  -。}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;}

运行结果:


0 0
原创粉丝点击