Alex Rivera | Logout

.NET2 DNS rejects hostnames over 126 characters as "too long"

Asked 2011-10-30T21:56:55.767
12

While working on a program I recently found that hostnames in .net (or at least in the ping class) are not supposed to have more than 126 characters. The ping class throws an exception if a hostname is longer.

However Wikipedia states that up to 255 characters are allowed. And it looks that indeed there are machines with a hostname longer than 126 chars out there, so the question is: can this limit be changed, who is right and how to resolve names if it cannot?

Edit
Report

1 Answer

9

The .NET Dns class has a hard upper limit of 126 characters for hostnames (checked for .NET4).

However, you can use the lower-level Win32 DnsQuery method using P/Invoke to translate host names into IP addresses and then use those raw addresses with the .NET networking classes.

Here is a sample DnsAddr class using this approach:

public static class DnsAddr
{
    [DllImport("dnsapi", EntryPoint = "DnsQuery_W", CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)]
    private static extern int DnsQuery([MarshalAs(UnmanagedType.VBByRefStr)]ref string pszName, QueryTypes wType, QueryOptions options, int         aipServers, ref IntPtr ppQueryResults, int pReserved);

    [DllImport("dnsapi", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern void DnsRecordListFree(IntPtr pRecordList, int FreeType);

    public static IEnumerable<IPAddress> GetAddress(string domain)
    {
        IntPtr ptr1 = IntPtr.Zero;
        IntPtr ptr2 = IntPtr.Zero;
        List<IPAddress> list = new List<IPAddress>();
        DnsRecord record = new DnsRecord();
        int num1 = DnsAddr.DnsQuery(ref domain, QueryTypes.DNS_TYPE_A, QueryOptions.DNS_QUERY_NONE, 0, ref ptr1, 0);
        if (num1 != 0)
            throw new Win32Exception(num1);
        for (ptr2 = ptr1; !ptr2.Equals(IntPtr.Zero); ptr2 = record.pNext)
        {
            record = (DnsRecord)Marshal.PtrToStructure(ptr2, typeof(DnsRecord));
            list.Add(new IPAddress(record.ipAddress));
        }
        DnsAddr.DnsRecordListFree(ptr1, 0);
        return list;
    }

    private enum QueryOptions
    {     
        DNS_QUERY_NONE = 0,
    }

    private enum QueryTypes
    {
        DNS_TYPE_A = 1,
    }

    [StructLayout(LayoutKind.Sequential)]
    private struct DnsRecord
    {
        public IntPtr p
answered 2011-10-30T23:55:42.607

Your Answer