boost asio - 检查 ip 是否来自特定子网

use*_*620 2 c++ boost-asio

我必须检查 IP 地址是否属于预定义的子网。例如,IP 地址 192.168.0.1 位于 CIDR 范围 192.168.0.0/24 内。

我尝试过:

有一个方法:

is_subnet_of对于network_v4class,但没有类似的 for adress_v4. 我错过了什么?

sup*_*myz 7

    using namespace boost::asio;
    // make a subnet with 255.255.255.0
    ip::network_v4 subnet = ip::make_network_v4("192.168.0.0/24");
    // get all the hosts from this subnet
    ip::address_v4_range hosts = subnet.hosts();

    boost::system::error_code error_code;
    // create target address
    ip::address addr = ip::make_address("192.168.0.1", error_code);
    if (error_code)
    {
        throw std::invalid_argument(error_code.message());
    }

    // Now check if the address is one of the hosts in the subnet
    if(hosts.find(addr.to_v4()) != hosts.end()) {
        std::cout << "yes" << std::endl;
    }
Run Code Online (Sandbox Code Playgroud)