четверг, 16 февраля 2012 г.

Get dns cache entry C#


  [DllImport("kernel32.dll", SetLastError = true)]
        static extern IntPtr LoadLibrary(String dllName);

        [DllImport("kernel32", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]
        static extern IntPtr GetProcAddress(IntPtr hModule, string procName);

        public struct DnsCacheEntry
        {
            public IntPtr pNext;

            [MarshalAs(UnmanagedType.LPWStr)]
            public string pszName;

            public ushort wType;

            public ushort wDataLength;

            public ulong dwFlags;
        }

        [UnmanagedFunctionPointer(CallingConvention.StdCall)]
        public delegate bool GetDNSCacheInvoker(out IntPtr dns);

        private List<string> DomainSearch()
        {
            const int DNS_TYPE_A = 0;

            var result = new List<string>();

            var hModule = LoadLibrary("dnsapi.dll");

            IntPtr fptr = GetProcAddress(hModule, "DnsGetCacheDataTable");

            IntPtr dnsPtr;

            GetDNSCacheInvoker drs = (GetDNSCacheInvoker)Marshal.GetDelegateForFunctionPointer(fptr, typeof(GetDNSCacheInvoker));

            if (drs(out dnsPtr))
            {
                var dns = (DnsCacheEntry)Marshal.PtrToStructure(dnsPtr, typeof(DnsCacheEntry));

                NativeMethods.NetApiBufferFree(dnsPtr);

                var current = dns.pNext;

                if (dns.wType == DNS_TYPE_A) result.Add(dns.pszName);

                while (current != IntPtr.Zero)
                {
                    dns = (DnsCacheEntry)Marshal.PtrToStructure(current, typeof(DnsCacheEntry));

                    var old = current;

                    current = dns.pNext;

                    if (dns.wType == DNS_TYPE_A) result.Add(dns.pszName);

                    NativeMethods.NetApiBufferFree(old);
                }
            }

            return result;
        }

Комментариев нет:

Отправить комментарий