.NET Dns
类的主机名的硬上限为126个字符(检查.NET4).
但是,您可以使用DnsQuery
P/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)
两个信息都是正确的。
255 个字符的限制是指整个主机名(例如some.thing.example.com
)。
反过来,每个标签(例如example
或com
)仅限于 63 个字符。因此顶级域理论上对126
非点字符有限制。