-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDnsAnswer.cs
More file actions
52 lines (41 loc) · 1.75 KB
/
Copy pathDnsAnswer.cs
File metadata and controls
52 lines (41 loc) · 1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
namespace DnsMessageParser;
public record DnsAnswerItem(string DomainName, DnsType DnsType, DnsClass DnsClass, uint TimeToLive, string Data);
public class DnsAnswer(byte[] udpPacket)
{
public readonly List<DnsAnswerItem> DnsAnswers = ParseDnsAnswers(udpPacket);
public void AddDnsAnswer(DnsAnswerItem dnsAnswerItem)
{
DnsAnswers.Add(dnsAnswerItem);
}
private static List<DnsAnswerItem> ParseDnsAnswers(byte[] udpPacket)
{
var dnsAnswers = new List<DnsAnswerItem>();
var position = 12;
position = udpPacket.QuestionSectionSkippedPosition(position);
var answerCount = (udpPacket[6] << 8) | udpPacket[7];
for (var i = 0; i < answerCount; i++)
{
// Read domain name (can be compressed)
var domainName = udpPacket.ReadDomainName(ref position);
// Read DNS Type (2 bytes)
position += 2;
// Read DNS Class (2 bytes)
position += 2;
// Read TTL (4 bytes)
var ttl = (uint)((udpPacket[position] << 24) | (udpPacket[position + 1] << 16) |
(udpPacket[position + 2] << 8) | udpPacket[position + 3]);
position += 4;
// Read data length (2 bytes)
var dataLength = (ushort)((udpPacket[position] << 8) | udpPacket[position + 1]);
position += 2;
var ipAddress =
$"{udpPacket[position]}." +
$"{udpPacket[position + 1]}." +
$"{udpPacket[position + 2]}." +
$"{udpPacket[position + 3]}";
dnsAnswers.Add(new DnsAnswerItem(domainName, DnsType.A, DnsClass.In, ttl, ipAddress));
position += dataLength;
}
return dnsAnswers;
}
}