如本文标题所示,不要使用 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(); }}
}