ama*_*ang 8 c++ boost network-programming wlan boost-asio
在我的计算机(Surface Pro 2)上,只有一个网络适配器,它是一个无线LAN适配器.
我参与了一个小型的C++项目,它使用boost :: asio连接到localhost并完成它的工作,一切都很好.
但今天我发现,如果我从互联网断开WLAN,这个程序不起作用.
boost :: asio的解析器会抛出异常:
tcp::resolver::query query("localhost", "10127");
tcp::resolver resolver(io_service_);
tcp::resolver::iterator iterator;
try {
iterator = resolver.resolve(query);
}
catch (boost::system::system_error& e) {
log(e.what());
}
Run Code Online (Sandbox Code Playgroud)
并且错误消息是:请求的名称有效,但未找到所请求类型的数据.
ping到localhost就可以了.
我感到困惑,本地网络程序是否需要互联网?本地网络程序是否需要LAN适配器?为什么ping工作正常?
我在Linux机器上遇到了同样的问题,并查看了提升asio文档.您只需要向query构造函数添加一个flag参数:
tcp::resolver::query query("localhost","10127",tcp::resolver::query::canonical_name);
注意:完整范围的名称query是boost::asio::ip::tcp::resolver::query.
发生这种情况是因为此处传递的默认flags参数是boost::asio::ip::tcp::resolver::query::address_configured,这意味着如果为系统配置了非环回IPv4/IPv6地址,则调用应仅解析IPv4/IPv6地址.
I have no explanation of why you have this error. However, what I did in a project was not by specifying the port number directly, but rather by constructing the endpoint instance in two steps. I don't recall the rationale at the time for doing it this way, but it might help you.
我提出的解决方案是这样的:
ip::tcp::resolver::query query(ip::tcp::v4(), "localhost", ""); // empty service name
tcp::resolver::iterator it_endpoint = resolver.resolve(query);
ip::tcp::endpoint endpoint(ip::tcp::endpoint(*it_endpoint).address(), port);
Run Code Online (Sandbox Code Playgroud)
这是我所做的总结摘录,因此它可能无法按原样编译。
| 归档时间: |
|
| 查看次数: |
3205 次 |
| 最近记录: |