创建 DNS 响应消息

标签 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?

但如您所见,我对填写内容有一些疑问。 另外,我无法通过 rfc 找出 R_Data 和 res_record 为我所做的随机响应填写什么...

有人可以帮我解决这个问题吗?

最佳答案

你的方法从根本上来说是有缺陷的。您无法使用结构体来表示 DNS 数据包,因为 DNS 数据包中的字符串是可变长度的,即字符串后面的字段将根据前面字符串的长度在数据包中处于不同的偏移量。

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

这里有一个相当说明性的指南,说明 DNS 数据包应该是什么样子:http://www.tcpipguide.com/free/t_DNSMessageProcessingandGeneralMessageFormat.htm

关于创建 DNS 响应消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13497185/

相关文章:

c - C 中对变量求和的函数

c++ - 如何在代码块 IDE 中获取控制台输出

C - 字符串数组到字符数组

python - 在 python 中批量/批量 DNS 查找?

c++ - 确保套装新颖性的有效方法

dns - 将 ".local"子域重定向到单播 DNS

node.js - 如何发布nodejs网站

linux - 无法使用 heapster 和 kube-dns 在 Kubernetes 上解析 monitoring-influxdb

azure - Azure 上的通配符子域

c - 指针值是什么意思?