.NET2 DNS拒绝超过126个字符的主机名"太长"

Fin*_*riX 12 .net c# dns ping

在处理程序时,我最近发现.net中的主机名(或至少在ping类中)不应该超过126个字符.如果主机名更长,ping类将引发异常.

然而,维基百科声明最多允许255个字符.并且看起来确实存在主机名超过126个字符的计算机,所以问题是:这个限制是否可以更改,谁是正确的以及如果不能解析名称?

Ric*_*key 9

.NET Dns类的主机名的硬上限为126个字符(检查.NET4).

但是,您可以使用DnsQueryP/Invoke 的低级Win32 方法将主机名转换为IP地址,然后将这些原始地址与.NET网络类一起使用.

以下是DnsAddr使用此方法的示例类:

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 pNext;
        public string pName;
        public short wType;
        public short wDataLength;
        public int flags;
        public int dwTtl;
        public int dwReserved;
        public uint ipAddress;
    }
}
Run Code Online (Sandbox Code Playgroud)

这是一个示例测试程序:

class Program
{
    static void Main(string[] args)
    {
        var addresses = DnsAddr.GetAddress("google.com");
        foreach (var address in addresses)
            Console.WriteLine(address.ToString());
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的机器上产生这个输出:

173.194.33.51
173.194.33.50
173.194.33.49
173.194.33.52
173.194.33.48
Run Code Online (Sandbox Code Playgroud)


Den*_*nis 1

两个信息都是正确的。

255 个字符的限制是指整个主机名(例如some.thing.example.com)。

反过来,每个标签(例如examplecom)仅限于 63 个字符。因此顶级域理论上对126非点字符有限制。