首页 > 解决方案 > 传递变量或放置具有相同内容的 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,
尼科

标签: c++clientboost-asio

解决方案


变量的值是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 };

推荐阅读