首页 > 解决方案 > 从 'const char*' 到 'uint32_t {aka unsigned int}' 的无效转换 [-fpermissive]

问题描述

我正在尝试通过使用网络掩码执行 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;
    }
}

标签: c++socketsnetworkingip

解决方案


问题出在这些线上

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

您不能将字符串文字分配给整数变量。您需要将字符串文字的内容解析为它们的数字等价物。您可以使用类似的套接字 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

推荐阅读