【问题标题】:Boost::asio async_connect fails to solve when using "localhost" instead of "127.0.0.1"Boost::asio async_connect 在使用“localhost”而不是“127.0.0.1”时无法解决
【发布时间】:2020-10-02 09:30:05
【问题描述】:

我正在编写一个 tcp 异步客户端,但是当我使用“localhost”而不是“127.0.0.1”时它无法连接。我的意思是,127.0.0.1 效果很好,但 localhost 却惨遭失败。请帮助修复它或至少解释发生了什么?也许我错过了 tcp::resolver 及其结果/迭代器?

PD:有趣的是,当使用同步版本连接时,它适用于两个地址(我的意思是使用 boost::asio::connect(socket, endpoints, error);)

#include <iomanip>
#include <iostream>
#include <boost/asio.hpp>

using boost::asio::ip::tcp;

class client
{
public:
    client()
        : io_context(),
          acceptor(io_context),
          socket(io_context)
    {
    }

    void start(const char* host, const char* port)
    {
        tcp::resolver resolver(io_context);
        tcp::resolver::results_type endpoints = resolver.resolve(host, port);//

        socket.async_connect(endpoints->endpoint(), [=](boost::system::error_code error)
        {
            if (!error)
                std::cout << "Connecting to " << host << ":" << port << "\n";
            else
                start(host, port);
        });
    }

    void poll()
    {
        io_context.poll();
    }

private:
    boost::asio::io_context io_context;
    tcp::acceptor acceptor;
    tcp::socket socket;
};


int main(int argc, char* argv[])
{
    if (argc != 1 && argc != 3)
    {
        std::cout << "async.exe <host> <port>" << std::endl;
        return 0;
    }

    const char* host = (argc == 1 ? "localhost" : argv[1]);
    const char* port = (argc == 1 ? "5031" : argv[2]);

    try
    {
        std::cout << "Trying to connect to " << host << ":" << port << "...\n";

        client c;
        c.start(host, port);

        while (true)
        {
            c.poll();
            Sleep(100);
        }
    }
    catch (std::exception& e)
    {
        std::cerr << "Exception: " << e.what() << "\n";
    }

    return 0;
}

非常感谢。

【问题讨论】:

    标签: c++11 boost-asio


    【解决方案1】:

    我正好有这个问题。我发现使用 localhost 和使用 IP 地址(例如 127.0.0.1 或本地机器的 IP 地址)之间的区别在于 endpoints.size() 不同。 IP 地址 endpoints.size() 为 1,但 localhost endpoints.size() 为 2。如果我随后使用调试器向下钻取,我可以看到其中一个端点的 IP 地址为 127.0.0.1,另一个具有IP 地址为 0.0.0.0。对我来说,有时端点列表工作正常,有时它会失败,我希望这是因为这些端点中只有一个实际上提供了可靠的路由。解决方法很容易,但否则会出现奇怪的行为。如果我猜的话,我怀疑 localhost 同时提供 IP4 和 IP6 端点,而 IP4 地址只能生成 IP4 端点。但它仍然不应该失败。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-14
      • 2011-08-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多