首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ASIO UDP客户端从不接收消息

ASIO UDP客户端从不接收消息
EN

Stack Overflow用户
提问于 2019-09-09 00:27:23
回答 1查看 181关注 0票数 0

我正在尝试使用独立的ASIO/C++库编写一个带有用户提供的解析器(只是一个文本文件,其中包含几个可用于查询的IP地址)的DNS解析器,但每次尝试使接收器工作时都会失败。所有的解析器似乎都没有对我发送的查询做出响应(udp::receive_from)。但是,当我尝试将相同的解析器文件与外部库(如dnslib )一起使用时,它们的工作方式非常出色,所以问题出在我的代码中。下面是我用来向DNS服务器发送数据的代码。

代码语言:javascript
复制
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

代码语言:javascript
复制
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] == '\0' ){  // 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] == '\0' ){
                    len = j;
                    strncpy( *buf, (char*) &len, 1 );
                    ++( *buf );
                    strncpy( *buf, (char*) dnsname + index, j );
                    ( *buf ) += j;
                    found = true;
                    if( dnsname[index + j] != '\0' )
                        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;
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-09-10 01:04:51

至少有两个问题是为什么它对你不起作用。这些问题都可以归结为您发送的DNS数据包格式不正确。

这一行

代码语言:javascript
复制
unsigned char* question_start = netbuf + sizeof( DNSPktHeader ) + 1;

将指针放入缓冲区的位置比您想要的更远。它不是从位置12 (从0开始索引)开始编码的FQDN,而是从位置13开始。这意味着DNS服务器会看到长度为零的域名和一些垃圾记录类型和类,并忽略其余部分。所以它决定根本不回复你的问题。干掉+1就行了。

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

此外,尽管不直接对观察到的行为负责,但除非您以根用户身份(或在bind()上具有适当的功能)运行二进制文件,否则以下对linux的调用将无效,因为您正试图绑定到一个特权端口。

代码语言:javascript
复制
udp_socket.bind( udp::endpoint{ asio::ip::make_address( "127.0.0.1" ), 53 } );

而且,这个dns_qry.bitfields = 0x8;不会做你想要的事情。应该是dns_qry.bitfields = 0x80;

请查看thisthis RFC,以了解如何形成有效的DNS请求。

重要提示:我强烈建议您不要将C++与C混合使用,但既然您标记了C++并使用了Boost和libfmt,请坚持使用C++。用适当的C++版本(static_castreinterpret_cast等)替换所有C风格的类型转换。不要使用C风格的数组,而要使用std::array,不要使用strncpy等。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57843723

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档