C/C++ StringToAddress(字符串转 boost::asio::ip::address)

发布于:2024-05-11 ⋅ 阅读:(146) ⋅ 点赞:(0)

为什么不推荐 boost::asio::ip::address::from_string、boost::asio::ip::address::make_string 函数来把字符串转换为 ip 地址呢?

这是因为有平台、编译器兼容性,在 android 平台上面,使用这两个函数会导致崩溃问题,在一些 clang 编译器上面也会导致崩溃问题。

所以人们必须实现这两个函数。

    boost::asio::ip::address                                                StringToAddress(const char* s, boost::system::error_code& ec) noexcept;

    inline boost::asio::ip::address                                         StringToAddress(const std::string& s, boost::system::error_code& ec) noexcept { 
        return StringToAddress(s.data(), ec); 
    }

    inline boost::asio::ip::address                                         StringToAddress(const ppp::string& s, boost::system::error_code& ec) noexcept { 
        return StringToAddress(s.data(), ec); 
    }
 

源实现:

    // 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(); 
        }
    }
}


网站公告

今日签到

点亮在社区的每一天
去签到