创建DNS响应消息

时间:2012-11-21 16:02:29

标签: c dns

我想创建一个DNS响应以发送到我的浏览器。我在rfc中创建了一些结构:

//DNS header
struct DNS_HEADER
{
    unsigned short id; 
    unsigned char rd :1; 
    unsigned char tc :1; 
    unsigned char aa :1; 
    unsigned char opcode :4;
    unsigned char qr :1; 

    unsigned char rcode :4; 
    unsigned char cd :1;
    unsigned char ad :1; 
    unsigned char z :1;  
    unsigned char ra :1; 

    unsigned short q_count; 
    unsigned short ans_count; 
    unsigned short auth_count; 
    unsigned short add_count; 
};

#pragma pack(push, 1)
struct R_DATA
{
    unsigned short type;
    unsigned short _class;
    unsigned int ttl;
    unsigned short data_len;
};
#pragma pack(pop)

struct RES_RECORD
{
    unsigned char *name;
    struct R_DATA *resource;
    unsigned char *rdata;
};

现在我正在尝试填写此结构,以便我可以发送有效的DNS响应。我正在尝试使用ipaddres 112.12.12.12发送www.google.com(仅为了好玩)。

这就是我所拥有的:

dns = (DNS_HEADER*)malloc(sizeof(DNS_HEADER));
dns->id = (unsigned short) htons(GetCurrentProcessId()); // ID 
dns->qr = 1; // We give a response, Volgens RFC: (= query (0), or a response (1).)
dns->opcode = 0; // default
dns->aa = 0; //Not Authoritative,RFC: (= Authoritative Answer - this bit is valid in responses, and specifies that the responding name server is an authority for the domain name in question section.)
dns->tc = 0; // Not truncated
dns->rd = 1; // Enable recursion
dns->ra = 0; // Nameserver supports recursion?
dns->z = 0; //  RFC: (= Reserved for future use.  Must be zero in all queries and responses.)
dns->rcode = 0; // No error condition
dns->q_count = 0; // No questions!
dns->ad = 0; // How man resource records?
dns->cd = 0; // !checking
dns->ans_count = 1; // We give 1 answer
dns->auth_count = 0; // How many authority entries?
dns->add_count = 0; // How many resource entries?

但是你可以看到我对填写什么有一些疑问。 还有R_Data和res_record我无法通过rfc找到我要填写的随机响应...

有人可以帮我这个吗?

2 个答案:

答案 0 :(得分:0)

一些指示一目了然:您的回复中的id需要是您在查询中收到的ID。 q_count应为1并重复您收到的查询(在您的示例中,例如\x03www\x06google\x03com\x00\x00\x01\x00\x01www.google.com IN A)。 RFC1035第3.4.1节(在您的示例中它是rdata)中解释了\x70\x0c\x0c\x0c中需要的内容。

答案 1 :(得分:0)

您的方法存在根本缺陷。您不能用结构表示DNS数据包,因为DNS数据包中的字符串是可变长度的,即字符串后面的字段将在数据包中的不同偏移量,具体取决于前面字符串的长度。

你的struct有char指针代替每个字符串,每个指针通常是一个32位值,指向内存中的其他位置。因此,当您尝试发送内存中表示的结构时,您将发送或多或少的随机32位值来代替字符串。

以下是DNS数据包应该是什么样的说明性指南:http://www.tcpipguide.com/free/t_DNSMessageProcessingandGeneralMessageFormat.htm