2 // Mono.Net.Dns.DnsPacket
5 // Gonzalo Paniagua Javier (gonzalo.mono@gmail.com)
7 // Copyright 2011 Gonzalo Paniagua Javier
9 // Licensed under the Apache License, Version 2.0 (the "License");
10 // you may not use this file except in compliance with the License.
11 // You may obtain a copy of the License at
13 // http://www.apache.org/licenses/LICENSE-2.0
15 // Unless required by applicable law or agreed to in writing, software
16 // distributed under the License is distributed on an "AS IS" BASIS,
17 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 // See the License for the specific language governing permissions and
19 // limitations under the License.
22 using System.Collections.Generic;
26 namespace Mono.Net.Dns {
27 abstract class DnsPacket {
28 protected byte [] packet;
29 protected int position;
30 protected DnsHeader header;
32 protected DnsPacket ()
34 // Caller has to initialize packet, position and header
37 protected DnsPacket (int length)
38 : this (new byte [length], length)
42 protected DnsPacket (byte [] buffer, int length)
45 throw new ArgumentNullException("buffer");
47 throw new ArgumentOutOfRangeException("length", "Must be greater than zero.");
51 header = new DnsHeader(new ArraySegment<byte>(packet, 0, 12));
54 public byte [] Packet {
55 get { return packet; }
59 get { return position; }
62 public DnsHeader Header {
63 get { return header; }
66 protected void WriteUInt16 (ushort v)
68 packet [position++] = (byte) ((v & 0x0ff00) >> 8);
69 packet [position++] = (byte) (v & 0x0ff);
72 protected void WriteStringBytes (string str, int offset, int count)
74 for (int i = offset, c = 0; c < count; c++, i++)
75 packet [position++] = (byte) str [i]; // Don't care about encoding.
78 protected void WriteLabel (string str, int offset, int count)
80 packet [position++] = (byte) count;
81 WriteStringBytes (str, offset, count);
84 protected void WriteDnsName (string name)
86 if (!DnsUtil.IsValidDnsName (name))
87 throw new ArgumentException ("Invalid DNS name");
89 if (!String.IsNullOrEmpty (name)) {
90 int len = name.Length;
93 for (int i = 0; i < len; i++) {
100 WriteLabel (name, label_start, label_len);
101 label_start += label_len + 1; // Skip the dot
106 WriteLabel (name, label_start, label_len);
109 packet [position++] = 0;
112 protected internal string ReadName (ref int offset)
114 return DnsUtil.ReadName (packet, ref offset);
117 protected internal static string ReadName (byte [] buffer, ref int offset)
119 return DnsUtil.ReadName (buffer, ref offset);
122 protected internal ushort ReadUInt16 (ref int offset)
124 return (ushort)((packet[offset++] << 8) + packet[offset++]);
127 protected internal int ReadInt32 (ref int offset)
129 return (packet [offset++] << 24) + (packet [offset++] << 16) + (packet [offset++] << 8) + packet [offset++];