c++ - 传递变量或放置具有相同内容的 ip 字符串时,asio 客户端应用程序会产生不同的结果
问题描述
有些事情我无法弄清楚。
以下是来自 boost asio 的聊天客户端示例的部分代码:https ://www.boost.org/doc/libs/1_70_0/doc/html/boost_asio/example/cpp11/chat/chat_client.cpp
int Tcp::client(std::string peer_ip)
{
try
{
boost::asio::io_context io_context;
tcp::resolver resolver(io_context);
auto endpoints = resolver.resolve(peer_ip, "1975");
chat_client c(io_context, endpoints);
std::thread t([&io_context]() { io_context.run(); });
char line[chat_message::max_body_length + 1];
while (std::cin.getline(line, chat_message::max_body_length + 1))
{
chat_message msg;
msg.body_length(std::strlen(line));
std::memcpy(msg.body(), line, msg.body_length());
msg.encode_header();
c.write(msg);
}
c.close();
t.join();
}
catch (std::exception &e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
当 peer_ip 变量如上所述传递给解析器时,我得到: Exception: resolve: Host not found (authoritative)
auto endpoints = resolver.resolve(peer_ip, "1975");
如果 IP 地址字符串如下所示,则客户端工作并与服务器对话。
auto endpoints = resolver.resolve("13.58.174.105", "1975");
我还尝试传递一个 const 变量和一个引用,使变量 std::move,但不知何故我的努力没有奏效。
你知道问题出在哪里,我应该怎么做吗?
TIA,
尼科
解决方案
变量的值是peer_ip
多少?如果它也是“13.58.174.105” ,那就很奇怪了。
否则它只是意味着无法将主机名解析为 IP 地址。
如果peer_ip
已知始终包含 IP 地址,则无需解析任何内容,您只需解析地址即可:
std::string peer_ip = "127.0.0.1";
tcp::endpoint endpoint {
boost::asio::ip::address_v4::from_string(peer_ip.c_str()), 1975 };
推荐阅读
- c# - 如何根据检查的真假门位置平滑移动场景视图相机?
- c# - 为什么我的全局对象实例不断重置?
- javascript - 如何使我的代码在 javascript 中同步
- machine-learning - 如何找到将用于 ML 模型的超参数调整的参数的最佳值?
- python - 如何使用 Google Drive API 计算(子)文件夹中的每个文件?
- node.js - 如何处理节点/快递中未知数量的参数
- aframe - 如何在附加到 gltf 元素的自定义组件内引用多种材料
- html - 如何将中间项目居中在列表中
- r - 删除为反应性数据框创建的 R 闪亮应用程序中的标记
- linux - java本机内存泄漏故障排除