2 // Mono.Net.Dns.DnsUtil
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;
25 namespace Mono.Net.Dns {
26 static class DnsUtil {
27 // RFC 2181 - Section 11
28 public static bool IsValidDnsName (string name)
33 int len = name.Length;
37 for (int i = 0; i < len; i++) {
40 if (i == 0 && len > 1)
41 return false; // Can't begin with a dot unless it's "."
42 if (i > 0 && part_length == 0)
43 return false; // No ".." allowed
54 public static int GetEncodedLength (string name)
56 if (!IsValidDnsName (name))
59 if (name == String.Empty)
62 int len = name.Length;
63 if (name [len - 1] == '.')
64 return len + 1; // (length + label + ... + \0)
65 return len + 2; // need 1 more for the second to last label length
68 public static int GetNameLength (byte [] buffer)
70 return GetNameLength (buffer, 0);
73 public static int GetNameLength (byte [] buffer, int offset)
76 throw new ArgumentNullException ("buffer");
77 if (offset < 0 || offset >= buffer.Length)
78 throw new ArgumentOutOfRangeException ("offset");
83 i = buffer [offset++];
85 return len > 0 ? --len : 0;
88 i = ((ptr & 0x3F) << 8) + buffer[offset++];
91 } else if (ptr >= 0x40) {
92 return -2; // Invalid ptr
97 return -1; // Invalid length
100 public static string ReadName (byte [] buffer, ref int offset)
103 throw new ArgumentNullException ("buffer");
104 if (offset < 0 || offset >= buffer.Length)
105 throw new ArgumentOutOfRangeException ("offset");
107 StringBuilder sb = new StringBuilder (32);
111 while (sb.Length < 256) {
113 if (no_ptr) offset++;
117 return sb.ToString ();
121 i = ((ptr & 0x3F) << 8) + buffer [off];
122 if (no_ptr) offset++;
126 } else if (i >= 0x40) {
127 return null; // Invalid ptr
130 for (int k = 0; k < i; k++)
131 sb.Append ((char) buffer [off + k]);
134 if (no_ptr) offset += i;
136 return null; // never reached