Search code examples
dnsgetaddrinfo

Why does getaddrinfo sometimes behave differently with "example.com" and "www.example.com"?


This is a code example from MSDN: getaddrinfo.

You can use "baidu.com" and "www.baidu.com" to test.


Solution

  • Because baidu.com and www.baidu.com are different addresses!

    www.example.com is registered in DNS with an A type record (or a CNAME, which points to an A record - this is slightly simplified) An A record is a name, in this case www that points to an IP Address 12.34.56.78. (as I'm sure you already know!)

    example.com can also have an A record registered (though not a CNAME) this is called the Apex (or naked!) domain. example.com's A record could very well point to 123.45.67.89

    A little history

    Part of the reason that this came about, is that in the early days of the internet, a server would have a hostname of something like LOCUS.UC.EDU because it can be difficult to know what services LOCUS might provide. you could attach the CNAME FTP.UC.EDU to point to that machine. that way people knew what services it offered. at that point, www was just another service, it had no special place in the collective consciousness. (all of this was happening over the decade or two that the internet was developing!) but you could also quite probably want [email protected] to work. so UC.EDU needed to be a host name also

    In actual fact it started with just the hostname (and host records that got telexed - I do love that fact) - but we'll ignore that for this case.

    back to the facts

    What usually - should - happen is that there is an A record registered at the Apex and a CNAME registered at www But there is certainly no requirement for this and you can have whatever records you wish at your domain.