Boost::asio async_connect 使用 "localhost" 而不是“127.0.0.1”时无法解决

Boost::asio async_connect fails to solve when using "localhost" instead of "127.0.0.1"

我正在编写一个 tcp 异步客户端,但是当我使用“localhost”而不是“127.0.0.1”时它无法连接。我的意思是,127.0.0.1 工作得很好,但 localhost 失败了。请帮助修复它或至少对发生的事情有任何解释?也许我误用了 tcp::resolver 及其 results/iterators?

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;
}

非常感谢。

我正好遇到这个问题。我在使用 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 端点。它仍然不应该失败。