ASIO UDP 客户端从不接收消息

ASIO UDP client never receiving messages

我正在尝试使用独立的 ASIO/C++ 库编写一个带有用户提供的解析器的 DNS 解析器(只是一个包含多个可用于查询的 IP 地址的文本文件),但我失败了使接收器工作的每一次尝试。所有的解析器似乎都没有响应(udp::receive_from)我发送的查询。但是,当我尝试将同一个解析器文件与 dnslib 等外部库一起使用时,它们的工作就像魅力一样,所以问题出在我的代码中。这是我用来向 DNS 服务器发送数据的代码。

struct DNSPktHeader
{
    uint16_t id{};
    uint16_t bitfields{};
    uint16_t qdcount{};
    uint16_t ancount{};
    uint16_t nscount{};
    uint16_t arcount{};
};

// dnsname, for example is -> google.com
// dns_resolver is a list of udp::endpoint of IPv4 address on port 53.
// ip is the final result
// returns 0 on success and negative value on failure

int get_host_by_name( char const *dnsname, std::vector<udp::endpoint> const & dns_resolvers, OUT uint16_t* ip )
{
    uint8_t netbuf[128]{};
    char const *funcname = "get_host_by_name";

    uint16_t const dns_id = rand() % 2345; // warning!!! Simply for testing purpose

    DNSPktHeader dns_qry{};
    dns_qry.id = dns_id;
    dns_qry.qdcount = 1;
    dns_qry.bitfields = 0x8; // set the RD field of the header to 1

    // custom_htons sets the buffer pointed to by the second argument netbuf
    // to the htons of the first argument
    custom_htons( dns_qry.id, netbuf + 0 );
    custom_htons( dns_qry.bitfields, netbuf + 2 );
    custom_htons( dns_qry.qdcount, netbuf + 4 );
    custom_htons( dns_qry.ancount, netbuf + 6 );
    custom_htons( dns_qry.nscount, netbuf + 8 );
    custom_htons( dns_qry.arcount, netbuf + 10 );

    unsigned char* question_start = netbuf + sizeof( DNSPktHeader ) + 1;
    // creates the DNS question segment into netbuf's specified starting index
    int len = create_question_section( dnsname, (char**) &question_start, thisdns::dns_record_type::DNS_REC_A, 
        thisdns::dns_class::DNS_CLS_IN );
    if( len < 0 ){
        fmt::print( stderr, "{}: {} ({})\n", funcname, dnslib_errno_strings[DNSLIB_ERRNO_BADNAME - 1], dnsname );
        return -EFAULT;
    }
    len += sizeof( DNSPktHeader );
    fmt::print( stdout, "{}: Submitting DNS A-record query for domain name ({})\n", funcname, dnsname );
    asio::error_code resolver_ec{};

    udp::socket udp_socket{ DNSResolver::GetIOService() };
    udp_socket.open( udp::v4() );
    // set 5 seconds timeout on receive and reuse the address
    udp_socket.set_option( asio::ip::udp::socket::reuse_address( true ) );
    udp_socket.set_option( asio::detail::socket_option::integer<SOL_SOCKET, SO_RCVTIMEO>{ 5'000 } );
    udp_socket.bind( udp::endpoint{ asio::ip::make_address( "127.0.0.1" ), 53 } );
    std::size_t bytes_read = 0, retries = 1;
    int const max_retries = 10;
    asio::error_code receiver_err{};
    uint8_t receive_buf[0x200]{};
    udp::endpoint default_receiver{};

    do{
        udp::endpoint const & resolver_endpoint{ dns_resolvers[retries] };
        int bytes_sent = udp_socket.send_to( asio::buffer( netbuf, len ), resolver_endpoint, 0, resolver_ec );
        if( bytes_sent < len || resolver_ec ){
            fmt::print( stderr, "{}: (found {}, expected {})\n", funcname, i, sizeof( DNSPktHeader ) );
            return -EFAULT;
        }
        // ======== the problem ==============
        bytes_read = udp_socket.receive_from( asio::buffer( receive_buf, sizeof( receive_buf ) ), default_receiver, 0,
            receiver_err );
        // bytes_read always return 0
        if( receiver_err ){
            fmt::print( stderr, "{}\n\n", receiver_err.message() );
        }
    } while( bytes_read == 0 && retries++ < max_retries );

    //...
}

我已经尽力了,但显然还不够。你能看看这个并帮助找出问题所在吗?这是我第一次在任何实际项目中使用 ASIO。

不知道这是否相关,但这里是 create_question_section

int create_question_section( const char *dnsname, char** buf, thisdns::dns_record_type type, thisdns::dns_class class_ )
{
    char const *funcname = "create_question_section";
    if( dnsname[0] == '[=11=]' ){  // Blank DNS name?
        fmt::print( stderr, "{}: Blank DNS name?\n", funcname );
        return -EBADF;
    }

    uint8_t len{};
    int index{};
    int j{};
    bool found = false;
    do{
        if( dnsname[index] != '.' ){
            j = 1;
            found = false;
            do{
                if( dnsname[index + j] == '.' || dnsname[index + j] == '[=11=]' ){
                    len = j;
                    strncpy( *buf, (char*) &len, 1 );
                    ++( *buf );
                    strncpy( *buf, (char*) dnsname + index, j );
                    ( *buf ) += j;
                    found = true;
                    if( dnsname[index + j] != '[=11=]' )
                        index += j + 1;
                    else
                        index += j;
                } else{
                    j++;
                }
            } while( !found && j < 64 );
        } else{
            fmt::print( stderr, "{}: DNS addresses can't start with a dot!\n", funcname );
            return -EBADF;  // DNS addresses can't start with a dot!
        }
    } while( dnsname[index] );
    uint8_t metadata_buf[5]{};

    custom_htons( (uint16_t)type, metadata_buf + 1 );
    custom_htons( (uint16_t)class_, metadata_buf + 3 );
    strncpy( *buf, (char*) metadata_buf, sizeof(metadata_buf) );

    return sizeof( metadata_buf ) + index + 1;
}

至少有两个问题导致它对您不起作用。归根结底就是你发出的DNS包格式不对。

这一行

unsigned char* question_start = netbuf + sizeof( DNSPktHeader ) + 1;

将指针设置到比您想要的更远的缓冲区位置。编码的 FQDN 不是从位置 12(从 0 开始索引)开始,而是从位置 13 开始。这意味着 DNS 服务器看到零长度域名和一些垃圾记录类型和 class 并忽略其余部分.因此它决定根本不响应您的查询。只需删除 +1.

另一个可能的问题是用 custom_htons() 对所有记录进行编码。我不知道它是如何实现的,所以无法告诉您它是否正常工作。

此外,虽然不直接对您观察到的行为负责,但以下对 bind() 的调用将产生零效果,除非您 运行 二进制文件作为根用户(或在 [=39= 上具有适当的功能) ]) 因为你正试图绑定到一个特权端口

udp_socket.bind( udp::endpoint{ asio::ip::make_address( "127.0.0.1" ), 53 } );

另外,这个 dns_qry.bitfields = 0x8; 不符合您的要求。应该是 dns_qry.bitfields = 0x80;.

查看 this and this RFC 以获取有关如何形成有效 DNS 请求的参考。

重要说明:我强烈建议您不要将 C++ 与 C 混合使用。选择一个,但由于您标记了 C++ 并使用了 Boost 和 libfmt,因此请坚持使用 C++。用适当的 C++ 版本(static_castreinterpret_cast 等)替换所有 C 风格的转换。不要使用 C 风格的数组,使用 std::array,不要使用 strncpy,等等