C/C++ 不要使用 boost::asio::ip::address::from_string 函数来转换字符串为IP地址

如本文标题所示,不要使用 boost::asio::ip::address::from_string 函数来转换字符串为IP地址,它可能导致崩溃。

这是因为 boost::asio::ip::address::from_string 函数实现并不安全有问题,在 Android 平台NDK优化编译的情况下,100%会导致程序各种崩溃。

无论是传递 char*、还是 std::string,都会导致崩溃,跟字符串长度、或者结尾NULL字节是没有任何关系的。

即便是在 GCC/VC++ 上面也有一定崩溃的风险,代替  boost::asio::ip::address::from_string 函数的实现可以参考本文下述的 C/C++ 安全实现。


即;通过C语言 posix/socket 函数库来处理,并且把结果在转换成 boost::asio::ip::address 就可以了。

源实现:

    // On the Android platform, call: boost::asio::ip::address::from_string function will lead to collapse, 
    // Only is to compile the Release code and opened the compiler code optimization.
    boost::asio::ip::address StringToAddress(const char* s, boost::system::error_code& ec) noexcept {
        ec = boost::asio::error::invalid_argument;
        if (NULL == s || *s == '\x0') {
            return boost::asio::ip::address_v4::any();
        }

        struct in_addr addr4;
        struct in6_addr addr6;
        if (inet_pton(AF_INET6, s, &addr6) > 0) {
            boost::asio::ip::address_v6::bytes_type bytes;
            memcpy(bytes.data(), addr6.s6_addr, bytes.size());

            ec.clear();
            return boost::asio::ip::address_v6(bytes);
        }
        else if (inet_pton(AF_INET, s, &addr4) > 0) {
            ec.clear();
            return boost::asio::ip::address_v4(htonl(addr4.s_addr));
        }
        else {
            return boost::asio::ip::address_v4::any(); 
        }
    }
}

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-31 10:54:06       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-31 10:54:06       100 阅读
  3. 在Django里面运行非项目文件

    2024-03-31 10:54:06       82 阅读
  4. Python语言-面向对象

    2024-03-31 10:54:06       91 阅读

热门阅读

  1. [笔记] BAD PASSWORD ,linux 修改密码历程

    2024-03-31 10:54:06       43 阅读
  2. OpenCV联通组件扫描

    2024-03-31 10:54:06       40 阅读
  3. Leetcode 643. 子数组最大平均数 I

    2024-03-31 10:54:06       39 阅读
  4. Timofey and a tree(思维题)

    2024-03-31 10:54:06       36 阅读
  5. 【二十六】【算法分析与设计】分治(1)

    2024-03-31 10:54:06       33 阅读
  6. [leetcode] 290. 单词规律

    2024-03-31 10:54:06       39 阅读
  7. 好用的编辑器Typora分享

    2024-03-31 10:54:06       35 阅读