【问题标题】:invalid conversion from ‘const char*’ to ‘uint32_t {aka unsigned int}’ [-fpermissive]从‘const char*’到‘uint32_t {aka unsigned int}’的无效转换[-fpermissive]
【发布时间】:2019-10-30 05:19:51
【问题描述】:

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

【问题讨论】:

  • 请阅读minimal reproducible example 并在问题中包含一个。请不要包含代码的链接或图像
  • 请通过editing将该信息添加到您的问题中。
  • 我添加了代码
  • 在尝试编写代码来做网络工作之前,您真的只需要学习语言。
  • @MeriemOUADAH “这就是我来这里的目的” 不幸的是,这与本网站的目的不符。你不能通过参加这里来真正学习语言。该站点旨在构建一个常见问题解答,例如重复性编程问题的存储库,并帮助解决这些问题以供将来研究。你的问题太基本了,不属于这一类。如前所述,在此处提问之前先从 好书 中学习。

标签: c++ sockets networking ip


【解决方案1】:

问题出在这几行

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

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

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

【讨论】:

  • 我做了同样的事情并且它有效,但在我的情况下,我想要转换的 ip 地址在变量“s”中,所以当我这样做时它不起作用:int32_t ip = inet_addr (s); // 要检查的值
  • @MeriemOUADAH inet_addr()const char * 作为输入。假设变量是std::string,只需调用它的c_str() 方法:inet_addr(s.c_str())
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多