判断两台设备是否属于同一子网的简易程序(C++实现)

给定ip地址与子网掩码,通过与运算判断是否属于同一子网:

#include<iostream>
#include<string>
#include<vector>

namespace Address{
    class Ip_Mask_Address
    {
    public:
        explicit Ip_Mask_Address(const std::string& ipaddress
                                ,const std::string& ipmask)
                :ip_adress(ipaddress),ip_mask(ipmask)
                {}
    private:
        void GetBinaryAdress(std::vector<int>& vec,const std::string& adress); 
    public:
        const std::string GetNetAddress();
        const std::string GetIpAddress() const{return ip_adress;}
        const std::string GetIpMask() const{return ip_mask;}
    private:
        std::string ip_adress;
        std::string ip_mask;
    };

    void Ip_Mask_Address::GetBinaryAdress(std::vector<int>& vec,const std::string& adress){
        std::string temp = "";
        for(auto& str:adress){
            if(str != '.'){
                temp += str;
            }else{
                vec.push_back(std::stoi(temp));
                temp = "";
            }
        }
        vec.push_back(std::stoi(temp));
    }

    const std::string Ip_Mask_Address::GetNetAddress(){
        std::vector<int>vec_ip,vec_mask;
        GetBinaryAdress(vec_ip,ip_adress),GetBinaryAdress(vec_mask,ip_mask);
        std::string net_address = "";
        for(unsigned int i = 0;i < 4;++i){
            net_address += (std::to_string(vec_ip.at(i) & vec_mask.at(i)));
            if(i != 3) net_address += '.';
        }
        return net_address;
    }

    bool IfBelongSameNetWork(Ip_Mask_Address& lhs,Ip_Mask_Address& rhs) {
        if(lhs.GetNetAddress() == rhs.GetNetAddress() && lhs.GetIpAddress() != rhs.GetIpAddress()){
            return true;
        }else return false;
    }
}

void test(){
    using namespace Address;
    Ip_Mask_Address address_1("192.168.182.131","255.255.255.0");
    Ip_Mask_Address address_2("192.168.26.131","255.255.255.0");
    if(IfBelongSameNetWork(address_1,address_2)) std::cout<<"They are in the same network\n";
    else std::cout<<"Not in the same network\n";
}

int main(){
    test();
    return 0;
}

上一篇:使用邻接表的方式实现图


下一篇:《Codeforces Round #742 (Div. 2)》