Click here to Skip to main content
Click here to Skip to main content

C# .NET DNS query component

By , 25 Oct 2005
 
Prize winner in Competition "C# Sep 2005"

Test Application

Introduction

This article demonstrates the form of DNS query messages and how to submit a request to a DNS server and interpret the result. I have wrapped this functionality up into a small easy-to-use C# assembly which you can easily deploy in your own applications to make ANAME, MX, NS and SOA queries. The assembly is entirely safe managed code, and it works just as well on Linux with the Mono CLR as it does on Windows. This article and the code supplied with it has been built from the information in RFC1035 - Domain names - implementation and specification.

Background

Until recently, spam was something which annoyed other people; I never got any. Somehow though, my email address has ended up on a mailing list and spam started showing up in my inbox. At first this was just a minor nuisance, but I expect my email address was sold on with thousands of others to other spammers and now I receive about 100 junk emails a day - a major annoyance. Why are they so convinced I need Viagra? I'm not that old...

Outlook to its credit has proven effective at detecting and destroying this junk, but I still didn't like the fact that it had to be picked up only to be discarded. The slightly protracted Send and Receive that normally indicates the arrival of a new attention-worthy email became more and more disappointing, and I wondered what someone would do if they were still stuck with a dial-up connection. It would be intolerable.

My solution was to create my own SMTP/POP3 server combination which could detect junk and destroy it, long before it could trouble Outlook, and this would present a good chance for me to get my .NET socket programming up to speed having used it very little in the past. I could use one of my Linux servers in Red Bus in London which I use for online game-hosting to host the mail server (via the glorious gift of Mono), but to do this would mean having to use completely managed C# without any P/Invoke calls. I got to work.

SMTP and POP3 are pretty simple text based standards to implement, but I hit a problem. In order for my SMTP server to relay my messages to other servers, an MX lookup would be required. An MX lookup is the act of retrieving the hostname(s) of one or more mail servers which handle a domain's email. A quick look at System.Net.Dns showed that the framework didn't support this, and as already mentioned I couldn't go down the Interop path. The only other alternatives were expensive commercial components which were out of the question because I certainly wasn't going to end up out of pocket on account of some spammers. My project had just got bigger.

So you want to ask a DNS server a question...

On the surface of it, DNS seems pretty straightforward, simply converting names to numbers, or retrieving other information about a domain. It's actually a huge and complicated subject and books on it tend to be quite wide. Thankfully, for the purpose of what we're doing we don't need to understand very much at all - just how to create a query, send it to a server, and interpret the response. The most common query that a DNS server deals with is the ANAME query, which maps domain names to IP addresses (codeproject.com to 209.171.52.99, for example). System.Net.Dns.GetHostByName performs ANAME lookups. Probably the next most common type of query is the MX query.

Unlike many of the internet protocols which are text based, DNS is a binary protocol. DNS servers are some of the busiest computers on the internet, and the overhead of string-parsing would make such a protocol prohibitive. To keep things fast and lean, UDP is the transport of choice being lightweight, connectionless and fast in comparison to TCP. To communicate with a DNS server, you simply throw a single UDP packet at it and it throws one back. Oh, and these packets cannot exceed 512 bytes in length. (Incidentally, many firewalls block UDP packets larger than 512 bytes in length.)

The diagram below shows the binary request I sent to my DNS server to look up the MX records for the domain microsoft.com and the corresponding response I received. To do this, I sent a 31 byte UDP packet to port 53 of my DNS server as shown below. It replied with a 97 byte response again on UDP port 53.

Both request and response share the same format, which starts with a 12 byte header block. This starts with a two byte message identifier. This can be any 16 bit value and is echoed in the first two bytes of the response, and is useful as it allows us to match up requests and responses as UDP makes no guarantees about the order in which things arrive. After that follows a two byte status field which in our request has just one single bit set, the recursion desired bit. Next comes a two byte value denoting how many questions there are in the request, in this case just 1. There then follows three more two byte values denoting the number of answers, name server records and additional records. As this is a request, all these are zero.

The rest of the request is our single question. A question consists of a variable length domain name, a two byte QTYPE and a two byte QCLASS in that order. Domain names are treated as a series of labels, labels being the words between dots. In our example microsoft.com consists of two labels, microsoft and com. Each label is preceded by a single byte specifying its length. The QTYPE denotes the type of record to retrieve, in this example, MX. QCLASS is Internet.

Test Application

The response we get back tells us that there are three inbound mail servers for the domain microsoft.com, maila.microsoft.com, mailb.microsoft.com and mailc.microsoft.com. All three have the same preference of 10. When sending mail to a domain, the mail server with the lowest preference should be tried first, then the next lowest etc. In this case, there is no preference difference and any of the three may be used. Let's look a bit more closely at the response.

You may have noticed that the first 31 bytes of the response are very similar to the request, the only difference being in the status field (bytes 2 & 3) and the answer count (bytes 6 & 7). The answer count tells us that three answers follow in the response. I refer those who are interested in the make up of the status field to the above RFC section 4.1.1, as I will not cover that here. You'll also notice that the question is echoed in the response, something which seems rather inefficient to me, but that's the standard. The first answer starts at byte 31 (0x1F).

The first part of any answer embeds the question in it so if you ask more than one question you know to which question the answer refers. A shortened form is used - rather than repeating the domain microsoft.com explicitly here which is wasteful when we've only got 512 bytes to play with. We reference the existing domain definition at byte 12 (0x0C). This requires just two bytes instead of 15 in our example. When examining the label length byte which precedes a label, if the two most significant bits are set, this denotes a reference to a previously defined domain name and the label does not follow here. The next byte tells you the position in the message of the existing domain name. Again the QTYPE and QCLASS follow, and then we start to see the part which is the answer.

The next four bytes represent the TTL (time to live) of the record. When a DNS server can't answer a question explicitly, it knows (or can find out) another server which can and asks that. It will then cache this answer for a certain period to improve efficiency. Every record in the cache has a TTL after which it will be destroyed and re-fetched from elsewhere if needed.

The next two bytes tell the size of the record, the next two the MX preference, and then follows the variable length domain name. Here we only specify the mailc part of the domain, and then again reference the rest of the domain name at byte 12 (to produce mailc.microsoft.com). Two almost identical records follow for maila.microsoft.com and mailb.microsoft.com.

Using the component

Now that everything is as clear as opaque crystal, let's look at the way you can use the supplied component to perform the domain look up for you. You will need to reference the assembly and import the Bdev.Net.Dns namespace. The following code illustrates the example above:

// Shameful hardcoding of my DNS server
IPAddress dnsServerAddress = IPAddress.Parse("194.74.65.68");

// Retrieve the MX records for the domain microsoft.com
MXRecord[] records = Resolver.MXLookup("microsoft.com", 
                                       dnsServerAddress);

// iterate through all the records and display the output
foreach (MXRecord record in records)
{
    Console.WriteLine("{0}, preference {1}", 
            record.HostName, record.Preference);
}

This uses a simplified form of the interface which is for MX records. You could also do the same query, with the code which follows:

// Further shameful hardcoding of my DNS server
IPAddress dnsServerAddress = IPAddress.Parse("194.74.65.68");

// create a request
Request request = new Request();

// add the question
request.AddQuestion(new Question("microsoft.com", 
                       DnsType.MX, DnsClass.IN));

// send the query and collect the response
Response response = Resolver.Lookup(request, dnsServerAddress);

// iterate through all the answers and display the output
foreach (Answer answer in Answers)
{
    MXRecord record = (MXRecord)answer.Record;
    Console.WriteLine("{0}, preference {1}", 
                      record.HostName, record.Preference);
}

Odds and ends

One annoyance with this component is that you have to explicitly tell the resolver the IP address of the DNS server to query, every time you do a look up. Ideally, it would use one of the default DNS servers so that you could leave this parameter out, but I have been unable to find a way of getting this information programmatically. If you know a way, then please let me know. It's haunting me.

Two things to note about DNS servers. Firstly, some support a TCP connection on port 53 in addition to UDP, and this can be used to get round the 512 byte limitation. Many do not, and I have not provided a TCP implementation. Secondly, although the protocol allows more than one question per request, many servers don't, probably to try and keep things within the 512 byte limit. I recommend that you only ever use a single question per request. If the response doesn't fit into 512 bytes, there is a truncation bit which is set in the status field.

Please report back to me any bugs/enhancements.

History

  • 2005-10-07:

    Initial release.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Rob Philpott
Architect
United Kingdom United Kingdom
I am a .NET architect/developer based in London working mostly on financial trading systems. My love of computers started at an early age with BASIC on a 3KB VIC20 and progressed onto a 32KB BBC Micro using BASIC and 6502 assembly language. From there I moved on to the blisteringly fast Acorn Archimedes using BASIC and ARM assembly.
 
I started developing with C++ since 1990, where it was introduced to me in my first year studying for a Computer Science degree at the University of Nottingham. I started professionally with Visual C++ version 1.51 in 1993.
 
I moved over to C# and .NET in early 2004 after a long period of denial that anything could improve upon C++.
 
Recently I did a bit of work in my old language of C++ and I now realise that frankly, it's a total pain in the arse.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Questionchange websitesmembercihepie17-Jan-12 1:58 
can i make a website routed to another, like if i go to google, i get to here?
QuestionYou code ported to ASP.NETmemberccsalway25-Sep-11 9:42 
Still a great article. The diagram explained it perfectly enabling me to port it to ASP.NET.
 
ASP.NET version
 
Thanks!
Questionfind local dns server addressmemberSCardosoPT21-Sep-11 7:03 
hello
 
just to let you know this option for finding local dns server configuration - from operational network interfaces, in case you can find it usefull.
 
link: how-to-get-local-dns-server-address
 
thanks for your code. it worked fine.
 
Sérgio
GeneralBug with domain names like '3-dveri.ru' (bad Regex)memberAlexey Spirin4-Apr-11 6:45 
Hello, thanks for component!
I found one bug: if I try to get MX records of domain 3-dveri.ru - there is exception
"The supplied domain name was not in the correct form
Parameter name: domain"
But this is good domain name and it has MX records.
So, I change this block of Question.cs:
			if (domain.Length ==0 || domain.Length>255 || !Regex.IsMatch(domain, @"^[a-z|A-Z|0-9|-|_]{1,63}(\.[a-z|A-Z|0-9|-|_]{1,63})+$"))
			{
				// domain names can't be bigger tan 255 chars, and individal labels can't be bigger than 63 chars
				throw new ArgumentException("The supplied domain name was not in the correct form", "domain");
			}
to
			// do a sanity check on the domain name to make sure its legal
			if (domain.Length ==0 || domain.Length>255)
			{
				// domain names can't be bigger tan 255 chars, and individal labels can't be bigger than 63 chars
				throw new ArgumentException("The supplied domain name was not in the correct form", "domain");
			}
 
		    try
		    {
		        System.Net.Dns.GetHostAddresses(domain);
		    }
		    catch {
                        throw new ArgumentException("The supplied domain name was not in the correct form", "domain");
		    }
 
Now component work's fine Smile | :)
GeneralRe: Bug with domain names like '3-dveri.ru' (bad Regex)memberpeteroblivo31-Jan-13 4:54 
^[a-z0-9][a-z0-9_\.-]{0,}[a-z0-9][\.][a-z0-9]{2,4}$
 
does the trick!
Questionhow to identify if ip is internal or externally hostedmemberbatghare9-Feb-11 17:02 
I want to identify if ip is internal ip within our network or ip belongs to externally hosted site
GeneralGet DNS Server Adress codememberIvan Rosales Rieloff15-Oct-10 10:09 
thanks for the code, here is code for find the dns server address if anyone wants use is a scratch.
 
For more info see :

http://msdn.microsoft.com/es-es/library/system.net.networkinformation.ipinterfaceproperties.dnsaddresses%28VS.90%29.aspx

 
Thansk for your work.
 
using System.Net.NetworkInformation;
private static IPAddress GetDnsAdress()
{
var interfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (var eth in interfaces)
{
if (eth.OperationalStatus == OperationalStatus.Up)
{
var ethProperties = eth.GetIPProperties();
var dnsHosts = ethProperties.DnsAddresses;
foreach (System.Net.IPAddress dnsHost in dnsHosts)
{
 
return dnsHost;
}
}
}
throw new InvalidOperationException("Dns Host Not found, see your network configuration");
}
GeneralMy vote of 5memberIvan Rosales Rieloff15-Oct-10 10:02 
es lo que buscaba
GeneralPowershellmemberarvidcarlander1-Oct-09 3:16 
This utility looks great. Can anyone suggest an easy way to call it from powershell?
 
Thanks in advance,
 
-Arvid Carlander
GeneralRe: Powershellmemberarvidcarlander1-Oct-09 4:36 
Ah, it was not as hard as I thought:
 

[reflection.assembly]::loadfile("Bdev.Net.Dns.dll")
$r=new-object bdev.net.dns.request
$type=[bdev.net.dns.dnstype]::SOA
$class=[bdev.net.dns.dnsclass]::IN
$q=new-object bdev.net.dns.question("mydomain.com",$type,$class)
$r.AddQuestion($q)
$dnsserver=[system.net.ipaddress]::parse("1.2.3.4")
$response=[bdev.net.dns.resolver]::lookup($r,$dnsserver)
$response.Answers[0].record.serial
 
Very quick, very simple, and very useful.
 
-Arvid
GeneralRe: Powershell [modified]memberMember 805097723-Nov-11 11:57 
Doesn't work for domains with hyphens in the name out of the box.
 
To those who use PowerShell and need to have the .dll file, I found the following worked:
 
1. Download the source files.
2. Download NUnit Framework, I grabbed the latest version from here: http://www.nunit.org/index.php?p=download[^]
3. Open the source files as a solution in Visual Studio - I am using Visual Studio 2010 Premium.
4. Mine made me convert it, so I did. Guess it was because it was written on an older version.
5. Right click the Bdev.Net.Dns.NUnit folder on the right under Solutions.
6. Properties.
7. Under the Build section change the output path. Now when you build the solution you will get the .dll file saved in the output location too.
 
Note: to work with domains that contained hyphens I changed line 45 of question.cs to the following:
 
if (domain.Length == 0 || domain.Length > 255 || !Regex.IsMatch(domain, @"^[a-z|A-Z|0-9|\-|_]{1,63}(\.[a-z|A-Z|0-9|\-|_]{1,63})+$"))
 
This Regex was taken from another post on this forum somewhere.

modified 23-Nov-11 18:24pm.

GeneralStrange regex:membertheit851414-Jul-09 10:07 
I was testing this to pull Gmail MX records from an external dns server, but the regex for your Question class is not working properly:
 
if (domain.Length ==0 || domain.Length>255 || !Regex.IsMatch(domain, @"^[a-z|A-Z|0-9|-|_]{1,63}(\.[a-z|A-Z|0-9|-|_]{1,63})+$"))
 
This regex does not match for an address like gmail-smtp-in.l.google.com
 
I used a Regex tester on that and it looks like if you swap - and _ in the regex, the regex will work:
 
^[a-z|A-Z|0-9|_|-]{1,63}(\.[a-z|A-Z|0-9|_|-]{1,63})+$
 
Now matches gmail-smtp-in.l.google.com according to my tests on regextester.com
 
-J
GeneralRe: Strange regex:memberMember 287962515-Mar-10 8:32 
One of my fellow devs just stumbled upon this and I didn't think to check here first.. The resolution he came up was was similar, but instead of changing the order we simply escape the hyphens.
 
@"^[a-z|A-Z|0-9|\-|_]{1,63}(\.[a-z|A-Z|0-9|\-|_]{1,63})+$"
GeneralHandling domains with hyphens? [modified]memberbenroberta8-Jul-09 3:24 
I've been trying to check domains using the following code:
    Public Shared Function MXRecordLookup(ByVal eMailAddress As String) As List(Of String)
 
        Dim lstServers As New List(Of String)
 
        ' Try each server in order until we get hits...
        For Each dnsServerAddress As IPAddress In ListMyDNS()
 
            Dim request As Request = New Request()
 
            ' add the question
            request.AddQuestion(New Question(GetMailDomain(eMailAddress), DnsType.MX, DnsClass.IN))
 
            ' send the query and collect the response
            Dim response As Response = Resolver.Lookup(request, dnsServerAddress)
 
            ' iterate through all the answers and add the servers to the list
            For Each answer As Answer In response.Answers
 
                Dim record As MXRecord = DirectCast(answer.Record, MXRecord)
                lstServers.Add(record.DomainName)
            Next
 
            ' Once we have servers stop
            If lstServers.Count > 0 Then Exit For
        Next
 
        Return lstServers
 
    End Function
This works in most cases, but will throw an error whenever the domain has a hyphen in it (i.e. does@not-work.com). I'm guessing there are other characters that will cause the same problem, but hyphens are the only one I've run into while running real email addresses through it. It fails on the line request.AddQuestion(New Question(GetMailDomain(eMailAddress), DnsType.MX, DnsClass.IN)), saying "The supplied domain name was not in the correct form." Any ideas how to fix this? Am I doing something wrong?
 
EDIT: I believe I've answered my own question. Editing the regex seems to have done the trick. Changed it to "^[a-zA-Z0-9_-]{1,63}(\.[a-zA-Z0-9_-]{1,63})+$"
 
modified on Wednesday, July 8, 2009 10:07 AM

GeneralhimemberMohannad_Dev8-Jun-09 1:46 
i have try to download the demo project .. but it do not work
GeneralHere's how to get DNS servers for the TCP/IP interfaces from the RegistrymemberREBratton5-Jun-09 12:30 
Public Shared Function FindDNSServers() As List(Of String)
Dim output As New List(Of String)
 
Dim start As RegistryKey = Registry.LocalMachine
Dim Interfaces As String = "SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces"
 
Dim InterfacesKey As RegistryKey = start.OpenSubKey(Interfaces)
 
For Each interfaceName As String In InterfacesKey.GetSubKeyNames
 
Dim InterfaceKey As RegistryKey = start.OpenSubKey(Interfaces & "\" & interfaceName)
 
Dim serverlist As String = InterfaceKey.GetValue("NameServer")
If serverlist <> "" Then output.AddRange(Split(serverlist, ","))
Next
 
Return output
 
End Function
 

Enjoy!
 
Rob
http://www.bratton-enterprises.com[^]
GeneralBug in ANameRecord.memberGilesb4-Jul-08 13:03 
I think your passing of the ip address bytes in the Constructor of ANameRecord is incorrect
 
It should be:
 
internal ANameRecord(Pointer pointer)
{
    byte[] b = new byte[4];
    for(int i = 0; i<4; i++)
        b[i] = pointer.ReadByte();
 
    _ipAddress = new IPAddress(b);
}
 
Then your program will return the correct ip of 69.10.233.10 for Codeproject.com instead of the one shown in your screenshot above.
 
Regards
 
Giles
GeneralRe: Bug in ANameRecord.memberGilesb13-Aug-08 1:07 
It seems that this project is not supported any more a better version can be found here
QuestionReverse DNS Lookup?membergonzasf24-Jun-08 5:40 
Hi! first of all, I must say you've donde an excellent work. Thank you for sharing it.
 
I have one question, I need to perform a Reverse DNS lookup on incoming emails IP addresses for an application I'm developing. I want to get the MX Records associated with the IP address to validate the sender. Can I make that with your code? I don't seem to figure out how.
 
Thanks in advance!
 
gonzasf

GeneralGetHostByName analogsmemberwassermann3-Jun-08 23:37 
Good morning, author!
It seems you know DNS in depth. So could you help me to solve one simple question?
 
I am developing a GetHostByName analog.
When I send DNS request which is a CNAME (e. g. www.google.com) servers send back one CNAME Resource Record and some A Resource Records.
So, to develop the analog of the GetHostByName() function, which receives std::string and returns only std::vector with IP addresses, I have to perform the next 3 steps:
1) Decode the DNS server`s answer.
2) Delete all Resource Records in the answer, with the exeption of the A Resource Records.
3) Extract ip fields from the A Resource Records and put them into the std::vector.
 
Am I right? Is this simple algorithm always valid? Or sometimes DNS servers send back responses containing only one CNAME record, implying I have to make recursive requests sometimes.
GeneralOver DesignedmemberRandy Charles Morin28-Apr-08 6:50 
That's a lot of code to do very little. I think you overdesigned the solution.
GeneralRe: Over DesignedmemberRob Philpott28-Apr-08 10:25 
Hey Randy,
 
Ok, fair dos. Take it or leave it. Unless you can come up with something a bit more specific than that comment then I'd advise against commenting in future.
 
Regards,
Rob Philpott.

GeneralRe: Good to learn frommemberChris Mankowski23-Mar-09 7:56 
I'm not sure if I agree with the vague OP's comment... but I really do like how intelligently the pointers were done without using unsafe code blocks. I think this implementation will be more robust, and less prone to error.
 
It would be nice if I could have more documentation on the methods and functions. Also a refresh with corrected bugs (mentioned in the comments here) would be nice as well.
QuestionDNS hackmemberRadu_209-Apr-08 23:04 
Is there a way in which I can hack the local windows dns to return an address for a specific host? For example for yahoo.com I want to get always 192.168.1.1? Thanks a lot.
 

AnswerRe: DNS hackmemberDrogas6-Jun-08 2:37 
Known way is to write to hosts file.
GeneralAdditional DNS Resourcesmemberj.monty5-Feb-08 4:42 
If you need additional record types, check out the following open source project I just wrapped up:
DnDns - A .NET DNS Resolver Library
 
later,
jason

GeneralHandling unknown resource record typesmemberMark Carrington22-Nov-07 1:38 
There's a bug in this code when it encounters an unknown resource record type in the response, e.g. an AAAA (IPv6 host) record.
 
In ResourceRecord.cs line 59, it attempts to skip over any data related to the unknown record using the overridden + operator in the Pointer class. However, that operator returns a new instance of the Pointer class, so when the code attempts to read the next resource record it is at the wrong position in the data.
 
To fix the problem, change the constructor of ResourceRecord and all its derived classes to accept a ref Pointer parameter, and change the Response constructor to pass the pointer to the constructors of the derived types with a ref modifier.
JokeRe: Handling unknown resource record typesmemberGreg Hauptmann22-Aug-10 1:05 
uggg - I just spend time fault finding this myself, and now I see someone had already mentioned it Smile | :)
GeneralBugmemberdubbele onzin15-Nov-07 3:07 
Hi, noticed a bug in your validation regexps in Question.cs:
 
Line 45 reads:
if (domain.Length ==0 || domain.Length>255 || !Regex.IsMatch(domain, @"^[a-z|A-Z|0-9|-|_]{1,63}(\.[a-z|A-Z|0-9|-|_]{1,63})+$"))

 
It should read:
if (domain.Length ==0 || domain.Length>255 || !Regex.IsMatch(domain, @"^[a-zA-Z0-9\-_]{1,63}(\.[a-zA-Z0-9\-_]{1,63})+$"))

 
This error would result in it refusing to accept fish-food.com, but it would accept fish|food.com.
 

GeneralImplemented also CNAME, PTR, TXT and ALL [modified]memberalphons11-Nov-07 23:23 
I don't know if the author of this article can make an update on this project, it seems his e-mail domain is not being used anymore...
 
-Alphons.
 
ps. I have published a new DNS.NET component.
 
It can be found here:
 
http://www.codeproject.com/KB/IP/DNS_NET_Resolver.aspx[^]
 
modified on Thursday, August 21, 2008 10:34 AM

QuestionRe: Implemented also CNAME, PTR, TXT and ALLmemberunencode16-Nov-07 7:51 
I'd love to get a copy of it, if you have it.
 
Thanks!
 
-Isaac
GeneralRe: Implemented also CNAME, PTR, TXT and ALLmemberScott Philip18-Nov-07 11:39 
I would like to have a copy of that, any chace you could send it to me, it would be much appreciated
 
Thanks!
 
Scott
GeneralRe: Implemented also CNAME, PTR, TXT and ALLmemberacidie4-Dec-07 21:02 
A fix for CNAME is to add;
 
case DnsType.CNAME: _record = new NSRecord(pointer); break;
 
in ResourceRecord.cs after line 53.
 
Is a quick/cheap fix but it works, as for the others, I don't know since I don't need them. But it shouldn't be hard using RCF 1035 as a guide.
 
.acidie
QuestionHow to get the Domain Entrys in NSmemberDavids Maguire15-Oct-07 21:58 
dears ,
is there a way to query a name server to get all the domain entrys stored on it
GeneralNS lookup via root serversmemberMrSmoofy21-Sep-07 10:20 
Ok I can't figure this out. I get an error of "Index was outside the bounds of the array."
 
What I want to do is lookup a domain name's name servers by asking the root servers.
 
Root Server are:
a.root-servers.org
b.root-servers.org
c.root-servers.org
d.root-servers.org
e.root-servers.org
f.root-servers.org
g.root-servers.org
h.root-servers.org
i.root-servers.org
j.root-servers.org
k.root-servers.org
l.root-servers.org
m.root-servers.org
 
When I look up a domain pointing at these dns servers I either get no error and no response or I get the error stated above.
 
How can I fix this?

 
Thanks,
Chris
GeneralRe: NS lookup via root serversmemberMiracle Zhou27-Sep-07 19:01 
You'll see this error when the returned UDP datapacket data size is over 512 bytes... you need to modify pointer.cs to fix it, kinda hack...
GeneralFantasticmemberwinstanley-john18-Sep-07 6:28 
This code is awsome thanks for this
GeneralGet local DNS in 1.1memberNJSMK13-Sep-07 4:20 
If like me you needed to use this excellent bit of code in .NET 1.1 and want to get local dns server(s), you can use the following method:
 
Add reference to System.Management
 
Import System.Management
 

Dim strQuery As String = _
"SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True"
Dim query As ManagementObjectSearcher = New ManagementObjectSearcher(strQuery)
Dim queryCollection As ManagementObjectCollection = query.Get()
Dim dnsservers As String()
 
For Each mo As ManagementObject In queryCollection
dnsservers = mo("DNSServerSearchOrder")
Exit For
Next

GeneralCorrection On Finding Local Connection DNS IPmemberMBrooker14-Aug-07 3:20 
public static ArrayList DnsServers()
{
ArrayList arrReturn = new ArrayList();

NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface n in adapters)
{
IPInterfaceProperties ipProps = n.GetIPProperties();
foreach (IPAddress ipAddr in ipProps.DnsAddresses)
{
arrReturn.Add(ipAddr.ToString());
}
}

return arrReturn;
}
 
MB
GeneralAutomatically find Your Computer's DNS ServersmemberMBrooker13-Aug-07 14:16 
http://www.java2s.com/Code/CSharp/Network/FindDNSServers.htm
 
MB
AnswerRe: Automatically find Your Computer's DNS Servers [modified]memberjlchereau24-Sep-08 6:42 
//The following requires using System.Net.NetworkInformation
NetworkInterface[] arrNetworkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface objNetworkInterface in arrNetworkInterfaces)
{
if ((objNetworkInterface.OperationalStatus == OperationalStatus.Up)
&& (objNetworkInterface.Speed > 0)
&& (objNetworkInterface.NetworkInterfaceType != NetworkInterfaceType.Loopback)
&& (objNetworkInterface.NetworkInterfaceType != NetworkInterfaceType.Tunnel))
{
foreach (IPAddress objDNSAddress in objNetworkInterface.GetIPProperties().DnsAddresses)
{
Console.WriteLine(objDNSAddress.ToString());
}
}
}
Good luck!
http://www.velodoc.com
 
modified on Wednesday, September 24, 2008 1:00 PM

GeneralMXLookup throws ArgumentException on domains containing a dashmemberClaus Conrad12-Jul-07 2:03 
See subject
AnswerRe: MXLookup throws ArgumentException on domains containing a dashmemberMiracle Zhou27-Sep-07 18:58 
I found this problem today, too. To resolve this issue, find Question.cs and locate line 45:
if (domain.Length ==0 || domain.Length>255 || !Regex.IsMatch(domain, @"^[a-z|A-Z|0-9|-|_]{1,63}(\.[a-z|A-Z|0-9|-|_]{1,63})+$"))
 
The regular expression is wrong. Change it to
if (domain.Length ==0 || domain.Length>255 || !Regex.IsMatch(domain, @"^[a-z|A-Z|0-9|\-|_]{1,63}(\.[a-z|A-Z|0-9|\-|_]{1,63})+$")), the problem will be resolved.
GeneralRe: MXLookup throws ArgumentException on domains containing a dashmemberellistours8-May-09 2:18 
Just change the regular expression in the constructor method of the Question class in question.cs to
^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,6}$
then this will work as expected.
 
BTW - Rob, nice work! Smile | :)
Generaldomain checkmemberHansWo5-Jun-07 22:36 
Hi there,
 
Nice component. I do however wonder if there is a small error in the domain regex (Question.cs). It does not match any domain with a name like aa-foo.com. Currently I have changed the regex to the following:
 
@"^([a-z0-9-])+(\.[a-z0-9-]+)*\.([a-z]{2,4})$"
 
Not sure if this will match all that is needed but I hope some of you can comment on this.
 
Regards,
 
Hans
GeneralRe: domain checkmemberMiracle Zhou27-Sep-07 19:04 
Hi Hans,
 
I used this one:
 
^[a-z|A-Z|0-9|\-|_]{1,63}(\.[a-z|A-Z|0-9|\-|_]{1,63})+$
 
Works fine for me.
 
Miracle

GeneralRe: domain check BAD AGAIN !memberAndyHo30-Oct-07 14:16 

the Regex should be: "^[a-zA-Z0-9_-]{1,63}(\.[a-zA-Z0-9_-]{1,63})+$"
 
Is the correct one, the other's fail because accept the pipe '|' character in the strings.
- Please read RegEx functions thoroughly! the minus"-" needs not to be escaped if its place is impossible to get a group of chars, like at last.
 
AndySoft
GeneralRequest class extensionmemberbombelek31-May-07 22:41 
It will be nice to extend Request class with public voi Reset() or Clear() memeber function, which just clears _questions list.
By the way, the component looks great !!!
QuestionNS queries and referralsmemberP. The Duck29-May-07 11:20 
I am using the query library to check the name server setting for a given domain as reported by the domain owner's registrar. To do so, I am querying against the root name servers. Unfortunately, I'm unable to distinguish between a referring name server and a name server that has the definitive NS record.
 
This results in an NS query that returns only the referring name servers for a great number of domains.
 
Has anyone dealt with something like this?
 

QuestionRe: NS queries and referralsmemberMrSmoofy8-Oct-07 16:13 
I need to know the same thing.
 
When I ask a root server (198.41.0.4) about a domain, I'm looking for the domains name servers, it comes back with more root servers so then I have to query 192.5.6.30 and then it tells me the name servers of the domain.
 
But how do I know I've found what I'm looking for. How do I tell a referral from the real name server records for a domain?

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130617.1 | Last Updated 25 Oct 2005
Article Copyright 2005 by Rob Philpott
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid