/// <summary> /// Wrapper method to perform DNS Query. /// </summary> /// <remarks>Makes DnsQuery a little more palatable.</remarks> /// <param name="domain">The domain.</param> /// <param name="dnsServerAddress">IPAddress of DNS server (may be null) </param> /// <param name="recordType">Type of DNS dnsRecord.</param> /// <param name="ppQueryResults">Pointer to pointer to query results.</param> /// <returns>Win32 status code.</returns> internal static int DnsQuery( string domain, IPAddress dnsServerAddress, DnsRecordType recordType, ref IntPtr ppQueryResults) { Debug.Assert(!string.IsNullOrEmpty(domain), "domain cannot be null."); IntPtr pServerList = IntPtr.Zero; try { pServerList = DnsNativeMethods.AllocDnsServerList(dnsServerAddress); return(DnsNativeMethods.DnsQuery( domain, recordType, DnsQueryOptions.DNS_QUERY_STANDARD, pServerList, ref ppQueryResults, 0)); } finally { // Note: if pServerList is IntPtr.Zero, FreeHGlobal does nothing. Marshal.FreeHGlobal(pServerList); } }
/// <summary> /// Perform DNS Query. /// </summary> /// <typeparam name="T">DnsRecord type.</typeparam> /// <param name="domain">The domain.</param> /// <param name="dnsServerAddress">IPAddress of DNS server to use (may be null).</param> /// <returns>The DNS record list (never null but may be empty).</returns> internal static List <T> DnsQuery <T>(string domain, IPAddress dnsServerAddress) where T : DnsRecord, new() { List <T> dnsRecordList = new List <T>(); // Each strongly-typed DnsRecord type maps to a DnsRecordType enum. DnsRecordType dnsRecordTypeToQuery = typeToDnsTypeMap.Member[typeof(T)]; // queryResultsPtr will point to unmanaged heap memory if DnsQuery succeeds. IntPtr queryResultsPtr = IntPtr.Zero; try { // Perform DNS query. If successful, construct a list of results. int errorCode = DnsNativeMethods.DnsQuery( domain, dnsServerAddress, dnsRecordTypeToQuery, ref queryResultsPtr); if (errorCode == Win32Success) { DnsRecordHeader dnsRecordHeader; // Interate through linked list of query result records. for (IntPtr recordPtr = queryResultsPtr; !recordPtr.Equals(IntPtr.Zero); recordPtr = dnsRecordHeader.NextRecord) { dnsRecordHeader = Marshal.PtrToStructure <DnsRecordHeader>(recordPtr); T dnsRecord = new T(); if (dnsRecordHeader.RecordType == dnsRecord.RecordType) { dnsRecord.Load(dnsRecordHeader, recordPtr); dnsRecordList.Add(dnsRecord); } } } else { throw new DnsException(errorCode); } } finally { if (queryResultsPtr != IntPtr.Zero) { // DnsQuery allocated unmanaged heap, free it now. DnsNativeMethods.FreeDnsQueryResults(queryResultsPtr); } } return(dnsRecordList); }
/// <summary> /// Free results from DnsQuery call. /// </summary> /// <remarks>Makes DnsRecordListFree a little more palatable.</remarks> /// <param name="ptrRecords">Pointer to records.</param> internal static void FreeDnsQueryResults(IntPtr ptrRecords) { Debug.Assert(!ptrRecords.Equals(IntPtr.Zero), "ptrRecords cannot be null."); DnsNativeMethods.DnsRecordListFree(ptrRecords, FreeType.RecordList); }