我有一个罐头复制器每 5 秒调用一次boost::asio::ip::tcp::resolver::resolve()
。localhost
它计算返回的端点数,并将该值与前一次迭代进行比较。
#include <boost/asio.hpp>
#include <iostream>
int main(int argc, char *argv[])
{
if ( argc < 3 ) {
std::cerr << argv[0] << " host port" << std::endl;
exit( EXIT_FAILURE );
}
const char* host = argv[1];
const char* service = argv[2];
boost::asio::io_service io_service;
boost::asio::ip::tcp::resolver resolver( io_service );
size_t previous = 0;
while ( true ) {
boost::asio::ip::tcp::resolver::iterator i(
resolver.resolve(
boost::asio::ip::tcp::resolver::query( host, service )
)
);
size_t count( 0 );
while ( i != boost::asio::ip::tcp::resolver::iterator() ) {
std::cout << i->endpoint() << std::endl;
++i;
++count;
}
std::cout << "got " << count << " addresses" << std::endl;
if ( previous == 0 ) {
previous = count;
}
assert( count == previous );
sleep( 5 );
}
}
示例会话
~> time ./addrinfo_asio localhost 80
...
127.0.0.1:80
got 1 addresses
[::1]:80
127.0.0.1:80
got 2 addresses
addrinfo_asio: addrinfo_asio.cc:35: int main(int, char**): Assertion `count == previous' failed.
Aborted (core dumped)
real 216m20.515s
user 0m0.181s
sys 0m0.193s
~>
你可以看到它找到一个端点(127.0.0.1:80)大约 3.5 小时,然后找到两个(127.0.0.1:80 和 [::1]:80)。我在想
- 为什么端点数从一变为二?
- 什么可能导致它?
解析 ipv4 和 ipv6 地址是有意的,我不想将查询限制为 ipv4。我意识到这种行为可能并不特定于 asio,我也有一个getaddrinfo
直接调用的复制器,它表现出相同的行为。如果相关的话,我的平台是 ppc64 RHEL 6.2。我没有尝试在其他地方复制。