Lookup SRV record in C#

Similar to MX lookup, we can use WINAPI DnsQuery from csharp to complete DNS SRV request.
You can take sources here.

public class nDnsQuery
    {
        public nDnsQuery()
        {
        }

        [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 string[] GetSRVRecords(string needle)
        {

            IntPtr ptr1 = IntPtr.Zero;
            IntPtr ptr2 = IntPtr.Zero;
            SRVRecord recSRV;
            if (Environment.OSVersion.Platform != PlatformID.Win32NT)
            {
                throw new NotSupportedException();
            }
            ArrayList list1 = new ArrayList();
            try
            {

                int num1 = nDnsQuery.DnsQuery(ref needle, QueryTypes.DNS_TYPE_SRV, QueryOptions.DNS_QUERY_BYPASS_CACHE, 0, ref ptr1, 0);
                if (num1 != 0)
                {
                    if (num1 == 9003)
                    {
                        list1.Add("DNS record does not exist");
                    }
                    else
                    {
                        throw new Win32Exception(num1);
                    }
                }
                for (ptr2 = ptr1; !ptr2.Equals(IntPtr.Zero); ptr2 = recSRV.pNext)
                {
                    recSRV = (SRVRecord)Marshal.PtrToStructure(ptr2, typeof(SRVRecord));
                    if (recSRV.wType == (ushort)QueryTypes.DNS_TYPE_SRV)
                    {
                        string text1 = Marshal.PtrToStringAuto(recSRV.pNameTarget);
                        text1 += ":" + recSRV.wPort;
                        list1.Add(text1);
                    }
                }
            }
            finally
            {
                nDnsQuery.DnsRecordListFree(ptr1, 0);
            }
            return (string[])list1.ToArray(typeof(string));
        }

        private enum QueryOptions
        {
            DNS_QUERY_ACCEPT_TRUNCATED_RESPONSE = 1,
            DNS_QUERY_BYPASS_CACHE = 8,
            DNS_QUERY_DONT_RESET_TTL_VALUES = 0x100000,
            DNS_QUERY_NO_HOSTS_FILE = 0x40,
            DNS_QUERY_NO_LOCAL_NAME = 0x20,
            DNS_QUERY_NO_NETBT = 0x80,
            DNS_QUERY_NO_RECURSION = 4,
            DNS_QUERY_NO_WIRE_QUERY = 0x10,
            DNS_QUERY_RESERVED = -16777216,
            DNS_QUERY_RETURN_MESSAGE = 0x200,
            DNS_QUERY_STANDARD = 0,
            DNS_QUERY_TREAT_AS_FQDN = 0x1000,
            DNS_QUERY_USE_TCP_ONLY = 2,
            DNS_QUERY_WIRE_ONLY = 0x100
        }

        private enum QueryTypes
        {
            DNS_TYPE_A = 0x0001,
            DNS_TYPE_MX = 0x000f,
            DNS_TYPE_SRV = 0x0021
        }

  
        [StructLayout(LayoutKind.Sequential)]
        private struct SRVRecord
        {
            public IntPtr pNext;
            public string pName;
            public ushort wType;
            public ushort wDataLength;
            public int flags;
            public int dwTtl;
            public int dwReserved;
            public IntPtr pNameTarget;
            public ushort wPriority;
            public ushort wWeight;
            public ushort wPort;
            public ushort Pad;
        }
    }
Enjoy!

11 comments:

Anonymous said...

very good article.
just a question, as far as you know, how can I specify a dns server to send the query to?
In your code, "aipServers" parameter is set to 0 witch means to use the local dns, what if I want to use another dns server?
thanks.

Ruslan said...

I have found hint on stackoverflow.com. Please take updated sources.

Anonymous said...

Great article!

I've looked so long for a reliable and easy method.

Thank you man! You made my day!

Anonymous said...

The SRVRecord definition needs some corrections (currently, a port >32767 will result in a negative port number).
Priority, Weight, and Port are all defined as "[...]The range is 0-65535. This is a 16 bit unsigned integer[...]" and must be of type ushort, not short.
http://tools.ietf.org/html/rfc2782

Ruslan said...

Thanks a lot Anonymous!
I have corrected types.

RobIII said...

You need to call DnsRecordListFree with DNS_FREE_TYPE value DnsFreeRecordList (e.g. DnsRecordListFree(ptr1, 1) ); if you don't you have a memory leak.

Ruslan said...

@Rob
I am calling nDnsQuery.DnsRecordListFree in finally section to free allocated memory.

Unknown said...

Very useful sample code. Noticed it was written a while back but still very useful. I searched for a while to find how to do SRV lookup from C# till I found your article. Thanks for your post.

Unknown said...

thanks a lot for your efforts Ruslan!,

I am having some issues in reading the SRV record from my local DNS server.

I have downloaded the code and compiled, it works if host = google.com or amazon.com SetDnsServer was commented out.

in my scenario when I set the host value to test domain like host = ad2016.rd.uk.biz

GetSRVRecords API's gets an error 9501 (DNS record does not exist)

please suggest if I am missing any bit

Many Thanks!



impotence said...

Stunning quest there. What occurred after? Good luck!

best erectile dysfunction pills said...

Useful information. Lucky me I discovered your site by accident, and I am shocked why this accident did not came about earlier! I bookmarked it.

HOWTO: Repair Logitech M325 Mouse

FixIt says that you will find single screw under CE label. It isn't always true.