简体   繁体   English

C++ 构建和发送 DNS 数据包

[英]C++ Build & Send DNS Packet

I'm working on a DNS resolver in C++, constructing the DNS header is giving me problems.我正在使用 C++ 开发 DNS 解析器,构建 DNS 标头给我带来了问题。 From what I've been able to gather, the header can be constructed through a struct.从我能够收集到的信息来看,标题可以通过一个结构来构建。

typedef struct {
  unsigned short id;

  unsigned char qr :1; // 0 query, 1 response
  unsigned char opcode :4; // 0 standard query
  unsigned char aa :1; // authoritive answer
  unsigned char tc :1; // truncated message
  unsigned char rd :1; // recursion desired

  unsigned char ra :1; // recursion available
  unsigned char z :3; // reserved
  unsigned char rcode :4;  // response code

  unsigned q_count :16; // number of question entries
  unsigned ans_count :16; // number of answer entries
  unsigned auth_count :16; // number of authority entries
  unsigned add_count :16; // number of resource entries
} HEADER;

typedef union {
  HEADER header;
  unsigned char packet_data[1024];
} DNS_PACKET;

I set the header values, place the header in DNS_PACKET, cast as (void *) and send the packet using sendto().我设置标头值,将标头放在 DNS_PACKET 中,转换为 (void *) 并使用 sendto() 发送数据包。

Viewing one of the sent packets in Wireshark shows that the bits are not being set in the correct locations.在 Wireshark 中查看发送的数据包之一显示位未设置在正确的位置。 For example I set q_count to 1, but Wireshark displays the packet with 256 questions.例如,我将 q_count 设置为 1,但 Wireshark 显示包含 256 个问题的数据包。

In all the documentation I've read, this appears to be a valid route to constructing a packet.在我读过的所有文档中,这似乎是构建数据包的有效途径。 Am I going about this incorrectly?我这样做是错误的吗? Is there a better method to construct a packet?有没有更好的方法来构造数据包?

I suggest you can use libnet to build the DNS packet.我建议您可以使用 libnet 来构建 DNS 数据包。 It will be much easier, never worry about the header's format.这会容易得多,不用担心标题的格式。

and you sure you have done the hton() or htonl() ?你确定你已经完成了 hton() 或 htonl() 吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM