c++windowsdns

How to get Windows domain name?


How can i get the domain name of the machine (if the machine is in fact joined to a domain)?

And, of course, if the machine is not joined to a domain the function should return

Notes:

Microsoft has a knowledge base article How to retrieve current user and domain names on Windows NT, Windows 2000, or Windows XP, which relies on getting the user's security token and calling LookupAccountSid.

Update One

i've also tried using ADs object to bind to the IADs interface of the domain:

IADs domain;
ADsGetObject("LDAP://rootDES", IDs, out domain);

problem with this approach is that:

Update Two:

Just to be clear what i want is:

enter image description here

Bonus Reading


Solution

  • Here you go:

    #include <Windows.h>
    #include <DSRole.h>
    
    #pragma comment(lib, "netapi32.lib")
    
    #include <stdio.h>
    
    int main(int argc, char ** argv)
    {
        DSROLE_PRIMARY_DOMAIN_INFO_BASIC * info;
        DWORD dw;
    
        dw = DsRoleGetPrimaryDomainInformation(NULL,
                                               DsRolePrimaryDomainInfoBasic,
                                               (PBYTE *)&info);
        if (dw != ERROR_SUCCESS)
        {
            wprintf(L"DsRoleGetPrimaryDomainInformation: %u\n", dw);
            return dw;
        }
    
        if (info->DomainNameDns == NULL)
        {
            wprintf(L"DomainNameDns is NULL\n");
        }
        else
        {
            wprintf(L"DomainNameDns: %s\n", info->DomainNameDns);
        }
    
        return 0;
    }
    

    Anybody using DsRoleGetPrimaryDomainInformation in production use should consider calling DsRoleFreeMemory to free the memory block when the information is no longer needed (as per discussion in the comments).

    The function returns three different domain names, e.g.:

    If the machine is not joined to a domain, then both Forest and dns are blank, with only NetBios name filled with the name of the workgroup, e.g.:

    The function also returns a flag indicating if the machine is joined to a domain:

    or not: