Get domain name

111,439

Solution 1

Why are you using WMI? Can't you use the standard .NET functionality?

System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;

Solution 2

I'm going to add an answer to try to clear up a few things here as there seems to be some confusion. The main issue is that people are asking the wrong question, or at least not being specific enough.

What does a computer's "domain" actually mean?

When we talk about a computer's "domain", there are several things that we might be referring to. What follows is not an exhaustive list, but it covers the most common cases:

  • A user or computer security principal may belong to an Active Directory domain.
  • The network stack's primary DNS search suffix may be referred to as the computer's "domain".
  • A DNS name that resolves to the computer's IP address may be referred to as the computer's "domain".

Which one do I want?

This is highly dependent on what you are trying to do. The original poster of this question was looking for the computer's "Active Directory domain", which probably means they are looking for the domain to which either the computer's security principal or a user's security principal belongs. Generally you want these when you are trying to talk to Active Directory in some way. Note that the current user principal and the current computer principal are not necessarily in the same domain.

Pieter van Ginkel's answer is actually giving you the local network stack's primary DNS suffix (the same thing that's shown in the top section of the output of ipconfig /all). In the 99% case, this is probably the same as the domain to which both the computer's security principal and the currently authenticated user's principal belong - but not necessarily. Generally this is what you want when you are trying to talk to devices on the LAN, regardless of whether or not the devices are anything to do with Active Directory. For many applications, this will still be a "good enough" answer for talking to Active Directory.

The last option, a DNS name, is a lot fuzzier and more ambiguous than the other two. Anywhere between zero and infinity DNS records may resolve to a given IP address - and it's not necessarily even clear which IP address you are interested in. user2031519's answer refers to the value of HTTP_HOST, which is specifically useful when determining how the user resolved your HTTP server in order to send the request you are currently processing. This is almost certainly not what you want if you are trying to do anything with Active Directory.

How do I get them?

Domain of the current user security principal

This one's nice and simple, it's what Tim's answer is giving you.

System.Environment.UserDomainName

Domain of the current computer security principal

This is probably what the OP wanted, for this one we're going to have to ask Active Directory about it.

System.DirectoryServices.ActiveDirectory.Domain.GetComputerDomain()

This one will throw a ActiveDirectoryObjectNotFoundException if the local machine is not part of domain, or the domain controller cannot be contacted.

Network stack's primary DNS suffix

This is what Pieter van Ginkel's answer is giving you. It's probably not exactly what you want, but there's a good chance it's good enough for you - if it isn't, you probably already know why.

System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName

DNS name that resolves to the computer's IP address

This one's tricky and there's no single answer to it. If this is what you are after, comment below and I will happily discuss your use-case and help you to work out the best solution (and expand on this answer in the process).

Solution 3

I found this question by the title. If anyone else is looking for the answer on how to just get the domain name, use the following environment variable.

System.Environment.UserDomainName

I'm aware that the author to the question mentions this, but I missed it at the first glance and thought someone else might do the same.

What the description of the question then ask for is the fully qualified domain name (FQDN).

Solution 4

If you want specific users to have access to all or part of the WMI object space, you need to permission them as shown here. Note that you have to be running on as an admin to perform this setting.

Solution 5

I know this is old. I just wanted to dump this here for anyone that was looking for an answer to getting a domain name. This is in coordination with Peter's answer. There "is" a bug as stated by Rich. But, you can always make a simple workaround for that. The way I can tell if they are still on the domain or not is by pinging the domain name. If it responds, continue on with whatever it was that I needed the domain for. If it fails, I drop out and go into "offline" mode. Simple string method.

 string GetDomainName()
    {
        string _domain = IPGlobalProperties.GetIPGlobalProperties().DomainName;

        Ping ping = new Ping();

        try
        {
            PingReply reply = ping.Send(_domain);

            if (reply.Status == IPStatus.Success)
            {
                return _domain;
            }
            else
            {
                return reply.Status.ToString();
            }
        }
        catch (PingException pExp)
        {
            if (pExp.InnerException.ToString() == "No such host is known")
            {
                return "Network not detected!";
            }

            return "Ping Exception";
        }
    }
Share:
111,439
Osvier
Author by

Osvier

osvier

Updated on July 16, 2020

Comments

  • Osvier
    Osvier almost 4 years

    My computer is in a Domain (Active Directory) and I need to get the domain name dynamically. I found the following code on the internet:

    SelectQuery query = new SelectQuery("Win32_ComputerSystem");
    using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query))
    {
        foreach (ManagementObject mo in searcher.Get())
        {
            if ((bool)mo["partofdomain"])
            {
                this.Domain = mo["domain"].ToString();
                break;
            }
        }
     }
    

    It works exactly as I want and returns exactly the domain name as I want (when I am logged as Administrator). If the user is not a Domain Admin, I have an Access denied exception.

    Does anybody know how to get the domain even with non-domain administrator users?

    NOTE: I have found this solution on Internet System.Environment.UserDomainName; but it only gives me a part of the domain name.

    I.e. my domain is: something.domain.com and the UserDomainName returns only something.

  • Rich
    Rich over 11 years
    Problem if the computer was removed from a domain - connect.microsoft.com/VisualStudio/feedback/details/549924/…
  • Mor Shemesh
    Mor Shemesh over 9 years
    You should change it to: System.Environment.UserDomainName
  • Vivekh
    Vivekh over 9 years
    Hey i am getting this from my local system but when i am hosting it in server i am able to get the PC-Name where i hosted but i want to get the name of the PC from which the user accessed my app. Is it possible
  • John Fairbanks
    John Fairbanks over 9 years
    This is a problem if you have a local user log in because it will then give the machine's name instead of the domain. (And yes, we hit this today and it caused us major grief). You probably don't want your answer to be dependent on the domain of the USER if you're trying to get the domain of the MACHINE.
  • Tim
    Tim over 9 years
    @John Never thought of that but it sounds very reasonable. How about this then; "System.DirectoryServices.ActiveDirectory.Domain", Haven't tried it out myself yet though.
  • John Fairbanks
    John Fairbanks over 9 years
    Yeah, never occurred to me either till someone did it yesterday... fortunately in our test lab and not at a customer site. The best solution seems to be the one marked here as the accepted solution - it doesn't require any new references and from what I understand some of the AD calls might require elevated privs.
  • Benjamin RD
    Benjamin RD about 9 years
    I used this code Request.ServerVariables["HTTP_HOST"] and works, but only can be used in the request context (controllers if you are using MVC)
  • AnthonyVO
    AnthonyVO over 8 years
    Found same issue as @Rich, the old value remains if the computer was removed from a domain. Could not follow his link.
  • DonBoitnott
    DonBoitnott almost 7 years
    GetComputerDomain has a companion, GetCurrentDomain that looks to be user-centric. What is the difference/benefit of using computer instead of user?
  • stb
    stb over 4 years
    @DonBoitnott A process is running as a user that can be in a different domain than the computer. This is possible if there is a "trust relationship" between those domains.
  • Ashish Sapkale
    Ashish Sapkale about 4 years
    This returned incorrect result for me. IPGlobalProperties.GetIPGlobalProperties().DomainName this worked just fine for me