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;
30 abstract class DnsPacket {
31 protected byte [] packet;
32 protected int position;
33 protected DnsHeader header;
35 protected DnsPacket ()
37 // Caller has to initialize packet, position and header
40 protected DnsPacket (int length)
41 : this (new byte [length], length)
45 protected DnsPacket (byte [] buffer, int length)
48 throw new ArgumentNullException("buffer");
50 throw new ArgumentOutOfRangeException("length", "Must be greater than zero.");
54 header = new DnsHeader(new ArraySegment<byte>(packet, 0, 12));
57 public byte [] Packet {
58 get { return packet; }
62 get { return position; }
65 public DnsHeader Header {
66 get { return header; }
69 protected void WriteUInt16 (ushort v)
71 packet [position++] = (byte) ((v & 0x0ff00) >> 8);
72 packet [position++] = (byte) (v & 0x0ff);
75 protected void WriteStringBytes (string str, int offset, int count)
77 for (int i = offset, c = 0; c < count; c++, i++)
78 packet [position++] = (byte) str [i]; // Don't care about encoding.
81 protected void WriteLabel (string str, int offset, int count)
83 packet [position++] = (byte) count;
84 WriteStringBytes (str, offset, count);
87 protected void WriteDnsName (string name)
89 if (!DnsUtil.IsValidDnsName (name))
90 throw new ArgumentException ("Invalid DNS name");
92 if (!String.IsNullOrEmpty (name)) {
93 int len = name.Length;
96 for (int i = 0; i < len; i++) {
103 WriteLabel (name, label_start, label_len);
104 label_start += label_len + 1; // Skip the dot
109 WriteLabel (name, label_start, label_len);
112 packet [position++] = 0;
115 protected internal string ReadName (ref int offset)
117 return DnsUtil.ReadName (packet, ref offset);
120 protected internal static string ReadName (byte [] buffer, ref int offset)
122 return DnsUtil.ReadName (buffer, ref offset);
125 protected internal ushort ReadUInt16 (ref int offset)
127 return (ushort)((packet[offset++] << 8) + packet[offset++]);
130 protected internal int ReadInt32 (ref int offset)
132 return (packet [offset++] << 24) + (packet [offset++] << 16) + (packet [offset++] << 8) + packet [offset++];