Wednesday, January 24, 2007

Getting the NETBIOS domain name

The task of figuring out your Active Directory NETBIOS domain name comes up now and again.  This is the process of turning something like "DC=yourdomain,DC=com" into something like "YOURDOMAIN".  This is important if you want to do things like prefix this name on the 'sAMAccountName' of a user for instance.  There are three ways of doing this (perhaps more).  I will cover each broadly.


Yes, that's right.  You can pretty much guess what it is by parsing the DN of the defaultNamingContext.  If you had something like "DC=yourdomain,DC=com", it seems a pretty good guess that the NETBIOS name is "YOURDOMAIN".  However, this method of course is not foolproof.  For whatever reason, your Active Directory admins might have decided to do something stupid - like say add a big dash (-) and some other random nonsense into the NETBIOS name.  Who knows why they do this, but hey, they can and do (I suspect they hate their users).  So, in this case, "DC=yourdomain,DC=com" might have a NETBIOS name of "YOURDOMAIN-CORP" for instance (it also means you have to type this every damn time you need to supply credentials as well in NT4 domain\user format).


You can simply use DsCrackNames to convert from DN format to NT4 format and it will work fine.  Pass the DN (e.g. "DC=yourdomain,DC=com") and you will get back the NETBIOS name.  This includes IADsNameTranslate if that is up your alley too.  Since there is no easy way to use either from .NET unless you build your own, this might not be your first choice.

LDAP Query

Finally, we get to the last method.  First, we connect to the RootDSE of the domain and inspect the following two properties:  "configurationNamingContext" and "defaultNamingContext".  Then we bind to the configuration partition (using the first of these properties) and perform the following search:  (&(objectCategory=crossRef)(nCName={0})) where {0} is the value you just got from the RootDSE for the 'defaultNamingContext'.  You should get one result.  Now, just read back the 'nETBIOSName' attribute and there you have it.

If you are shipping software that needs to do this, obviously you should use one of the last two methods.  Guessing probably will just not cut it for anything that is just not quick and dirty.