How to determine if a computer is connected to a domain?

How to determine if a computer is connected to an Active Directory domain (in workgroup mode)?

+55
c #
May 29 '09 at 14:20
source share
12 answers

You can run PInvoke for the Win32 API, such as NetGetDcName, which will return a blank / empty string for a computer that is not joined to the domain.

Even better is NetGetJoinInformation, which will tell you explicitly if the machine is not connected, in a workgroup or in a domain.

Using NetGetJoinInformation I put together this and it worked for me:

 public class Test { public static bool IsInDomain() { Win32.NetJoinStatus status = Win32.NetJoinStatus.NetSetupUnknownStatus; IntPtr pDomain = IntPtr.Zero; int result = Win32.NetGetJoinInformation(null, out pDomain, out status); if (pDomain != IntPtr.Zero) { Win32.NetApiBufferFree(pDomain); } if (result == Win32.ErrorSuccess) { return status == Win32.NetJoinStatus.NetSetupDomainName; } else { throw new Exception("Domain Info Get Failed", new Win32Exception()); } } } internal class Win32 { public const int ErrorSuccess = 0; [DllImport("Netapi32.dll", CharSet=CharSet.Unicode, SetLastError=true)] public static extern int NetGetJoinInformation(string server, out IntPtr domain, out NetJoinStatus status); [DllImport("Netapi32.dll")] public static extern int NetApiBufferFree(IntPtr Buffer); public enum NetJoinStatus { NetSetupUnknownStatus = 0, NetSetupUnjoined, NetSetupWorkgroupName, NetSetupDomainName } } 
+28
May 29 '09 at 2:40 p.m.
source share

Do not be fooled by pinvoke if you do not need it.

Reference System.DirectoryServices, then call:

 System.DirectoryServices.ActiveDirectory.Domain.GetComputerDomain() 

ActiveDirectoryObjectNotFoundException if the machine is not connected to a domain. The returned Domain object contains the Name property that you are looking for.

+91
Feb 16 2018-10-16
source share

You can also call using system.net

 string domain = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName 

If the domain string is empty, the machine is not bound.

Documentation on the returned property https://docs.microsoft.com/en-us/dotnet/api/system.net.networkinformation.ipglobalproperties.domainname?view=netframework-4.7.2#System_Net_NetworkInformation_IPGlobalProperties_DomainName

+19
Sep 11 '13 at 16:11
source share
 ManagementObject cs; using(cs = new ManagementObject("Win32_ComputerSystem.Name='" + System.Environment.MachineName + "'" )) { cs.Get(); Console.WriteLine("{0}",cs["domain"].ToString()); } 

This will allow you to get a domain. I believe that it will be empty or empty if you are part of a workgroup and not a domain.

Be sure to specify System.Management

+7
May 29 '09 at 14:29
source share

Just wanted to reset Rob code in VB:

  Public Class Test Public Function IsInDomain() As Boolean Try Dim status As Win32.NetJoinStatus = Win32.NetJoinStatus.NetSetupUnknownStatus Dim pDomain As IntPtr = IntPtr.Zero Dim result As Integer = Win32.NetGetJoinInformation(Nothing, pDomain, status) If (pDomain <> IntPtr.Zero) Then Win32.NetApiBufferFree(pDomain) End If If (result = Win32.ErrorSuccess) Then If (status = Win32.NetJoinStatus.NetSetupDomainName) Then Return True Else Return False End If Else Throw New Exception("Domain Info Get Failed") End If Catch ex As Exception Return False End Try End Function End Class Public Class Win32 Public Const ErrorSuccess As Integer = 0 Declare Auto Function NetGetJoinInformation Lib "Netapi32.dll" (ByVal server As String, ByRef IntPtr As IntPtr, ByRef status As NetJoinStatus) As Integer Declare Auto Function NetApiBufferFree Lib "Netapi32.dll" (ByVal Buffer As IntPtr) As Integer Public Enum NetJoinStatus NetSetupUnknownStatus = 0 NetSetupUnjoined NetSetupWorkgroupName NetSetupDomainName End Enum End Class 

Like Stefan's code here:

 Dim cs As System.Management.ManagementObject Try cs = New System.Management.ManagementObject("Win32_ComputerSystem.Name='" + System.Environment.MachineName + "'") cs.Get() dim myDomain as string = = cs("domain").ToString Catch ex As Exception End Try 


I believe that only the second code will let you know which area the computer has joined, even if the current user is NOT a member of the domain.

+5
Dec 05 2018-11-12T00:
source share

Environment variables may work for you.

 Environment.UserDomainName 

MSDN link for more details.

 Environment.GetEnvironmentVariable("USERDNSDOMAIN") 

I am not sure if this environment variable exists without being in the domain.

Correct me if I am wrong. Windows Admin Hickers - I believe that a computer can be in several domains, so it may be more important to know which domain you are in, and not in any domain.

+4
May 29 '09 at 14:53
source share

You can check the PartOfDomain property of the WMI class Win32_ComputerSystem. MSDN says:

Partoffomain

Data Type: boolean

Access Type: Read Only

If True, the computer is part of a domain. If the value is NULL, the computer is not in the domain or the status is unknown. if you disconnect the computer from the domain, the value will become false.

 /// <summary> /// Determines whether the local machine is a member of a domain. /// </summary> /// <returns>A boolean value that indicated whether the local machine is a member of a domain.</returns> /// <remarks>http://msdn.microsoft.com/en-us/library/windows/desktop/aa394102%28v=vs.85%29.aspx</remarks> public bool IsDomainMember() { ManagementObject ComputerSystem; using (ComputerSystem = new ManagementObject(String.Format("Win32_ComputerSystem.Name='{0}'", Environment.MachineName))) { ComputerSystem.Get(); object Result = ComputerSystem["PartOfDomain"]; return (Result != null && (bool)Result); } } 
+4
Apr 24 '13 at 13:34
source share

Here are my exception handling / comment methods that I developed based on a few responses in this post.

  • Gets the domain to which the computer is connected.
  • Returns only the domain name if the user is actually registered in the domain account.

     /// <summary> /// Returns the domain of the logged in user. /// Therefore, if computer is joined to a domain but user is logged in on local account. String.Empty will be returned. /// Relavant StackOverflow Post: http://stackoverflow.com/questions/926227/how-to-detect-if-machine-is-joined-to-domain-in-c /// </summary> /// <seealso cref="GetComputerDomainName"/> /// <returns>Domain name if user is connected to a domain, String.Empty if not.</returns> static string GetUserDomainName() { string domain = String.Empty; try { domain = Environment.UserDomainName; string machineName = Environment.MachineName; if (machineName.Equals(domain,StringComparison.OrdinalIgnoreCase)) { domain = String.Empty; } } catch { // Handle exception if desired, otherwise returns null } return domain; } /// <summary> /// Returns the Domain which the computer is joined to. Note: if user is logged in as local account the domain of computer is still returned! /// </summary> /// <seealso cref="GetUserDomainName"/> /// <returns>A string with the domain name if it joined. String.Empty if it isn't.</returns> static string GetComputerDomainName() { string domain = String.Empty; try { domain = System.DirectoryServices.ActiveDirectory.Domain.GetComputerDomain().Name; } catch { // Handle exception here if desired. } return domain; } 
+3
02 Oct '12 at 23:01
source share

You might want to try using the DomainRole WMI field. Values ​​0 and 2 indicate a stand-alone workstation and stand-alone server, respectively.

We use this for the XIA Configuration of our network audit software, so I immediately reinforced the method ...

 /// <summary> /// Determines whether the local machine is a member of a domain. /// </summary> /// <returns>A boolean value that indicated whether the local machine is a member of a domain.</returns> /// <remarks>http://msdn.microsoft.com/en-gb/library/windows/desktop/aa394102(v=vs.85).aspx</remarks> public bool IsDomainMember() { ManagementObject ComputerSystem; using (ComputerSystem = new ManagementObject(String.Format("Win32_ComputerSystem.Name='{0}'", Environment.MachineName))) { ComputerSystem.Get(); UInt16 DomainRole = (UInt16)ComputerSystem["DomainRole"]; return (DomainRole != 0 & DomainRole != 2); } } 
+1
Jan 23 '13 at 15:40
source share

If performance matters, use GetComputerNameEx :

  bool IsComputerInDomain() { uint domainNameCapacity = 512; var domainName = new StringBuilder((int)domainNameCapacity); GetComputerNameEx(COMPUTER_NAME_FORMAT.ComputerNameDnsDomain, domainName, ref domainNameCapacity); return domainName.Length > 0; } [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)] static extern bool GetComputerNameEx( COMPUTER_NAME_FORMAT NameType, StringBuilder lpBuffer, ref uint lpnSize); enum COMPUTER_NAME_FORMAT { ComputerNameNetBIOS, ComputerNameDnsHostname, ComputerNameDnsDomain, ComputerNameDnsFullyQualified, ComputerNamePhysicalNetBIOS, ComputerNamePhysicalDnsHostname, ComputerNamePhysicalDnsDomain, ComputerNamePhysicalDnsFullyQualified } 
+1
Feb 19 '16 at 16:01
source share

You can check using WMI :

 private bool PartOfDomain() { ManagementObject manObject = new ManagementObject(string.Format("Win32_ComputerSystem.Name='{0}'", Environment.MachineName)); return (bool)manObject["PartOfDomain"]; } 
+1
Jul 15 '17 at 15:36
source share

The proposed solution above returns false on the domain machine if the local user is registered.

The most reliable method I have found is through WMI:

http://msdn.microsoft.com/en-us/library/aa394102(v=vs.85).aspx (see domainrole)

0
Nov 18 '13 at 21:09
source share



All Articles