从“ const char *”到“ uint32_t {aka unsigned int}”的无效转换[-fpermissive]

时间:2019-06-16 08:39:33

标签: c++ sockets networking ip

我正在尝试通过对net mask进行and操作来检查ip地址是否在范围内,此代码给我以下错误:

invalid conversion from ‘const char*’ to ‘uint32_t {aka unsigned int}’ [-fpermissive]

我是c ++的初学者,对此有什么解决方案吗?

int main() {
    uint32_t ip = "192.168.2.1"; 
    // value to check 
    uint32_t netip = "192.168.2.0"; // network ip to compare with 
    uint32_t  netmask = "255.255.255.0"; // network ip subnet mask
    if (  (netip & netmask) == (ip & netmask)) {
        // is on same subnet... 
        std::cout << "On the same subnet" << std::endl;
    } else {
        // not on same subnet... 
        std::cout << "Not on the same subnet" << std::endl;
    }
}

1 个答案:

答案 0 :(得分:0)

问题出在这些线上

uint32_t ip = "192.168.2.1"; // value to check
uint32_t netip = "192.168.2.0"; // network ip to compare with
uint32_t netmask = "255.255.255.0"; // network ip subnet mask

您不能将字符串文字分配给整数变量。您需要将字符串文字的内容 parse 解析为其等效的数字。您可以为此使用套接字API函数,例如inet_addr(),例如:

uint32_t ip = inet_addr("192.168.2.1"); // value to check
uint32_t netip = inet_addr("192.168.2.0"); // network ip to compare with
uint32_t netmask = inet_addr("255.255.255.0"); // network ip subnet mask