32

Ex : I want something like abc.hyd.mycompany.com. My requirement is to parse this name and initialize appropriate service.

using System.Net;

Dns.GetHostName() // doesn't return fully qualified name it just gives "abc" 
David Thielen
  • 28,723
  • 34
  • 119
  • 193
user21246
  • 1,774
  • 3
  • 15
  • 15

3 Answers3

52

You may be able to get the whole DNS string like this:

System.Net.Dns.GetHostEntry("").HostName

We don't have full fledged DNS names where I work, but it does give me a three level faux domain name instead of just the hostname.

Edit 2011/03/17: Incorporated changes suggested by mark below.

Powerlord
  • 87,612
  • 17
  • 125
  • 175
  • 1
    Better still pass the empty string "" to GetHostEntry. This yields the same result, but feels better. – mark Mar 17 '11 at 16:41
  • @mark: You're right, it does, and it's one less instruction to process. I don't know how I missed that. Feels kind of weird updating an answer from two years ago, but... – Powerlord Mar 17 '11 at 18:11
  • Does this work the same on XP as Win7? The example code given before the recent edit gives qualified hostname on Win7 but only gives unqualified name on XP. Want code that works on both. Thanks. – Cincinnati Joe Mar 21 '11 at 14:54
  • @CincinnatiJoe: Odd, the old and new versions work identically on my WinXP SP3 work machine, which is located on the State of Michigan's internal network. I've updated the answer to still show the old version, in case there are issues like the one you experienced. – Powerlord Mar 21 '11 at 17:21
  • Actually, I was saying that the old approach doesn't work as expected on XP. Did a quick try with the revised approach and it also doesn't appear work on XP. Both work find on Win7. So may need another solution for getting qualified name on XP. – Cincinnati Joe Mar 22 '11 at 12:11
  • @CincinnatiJoe: Oh, OK. I blame the fact that is was Monday for me misreading it. ;) Out of curiosity, does the other answer help at all, or is that useless too? I'm still not sure why this doesn't work on your WinXP machine, though... it works fine on XP here. – Powerlord Mar 22 '11 at 13:43
13

I used this very similar method:

var serverName = System.Environment.MachineName; //host name sans domain
var fqhn = System.Net.Dns.GetHostEntry(serverName).HostName; //fully qualified hostname
popofef
  • 131
  • 1
  • 2
2

If the above doesn't work, you can also try retrieving it from the environment:

var dnsName = new StringBuilder();
dnsName.Append(Environment.GetEnvironmentVariable("COMPUTERNAME")).Append(".");
dnsName.Append(Environment.GetEnvironmentVariable("USERDNSDOMAIN"));
Powerlord
  • 87,612
  • 17
  • 125
  • 175
  • 8
    This may not work - USERDNSDOMAIN may not be the same as the domain that the machine belongs to. – pduncan Dec 04 '09 at 19:36