Getting a machine’s NetBIOS domain name in C#
March 11, 2009 22 Comments
I tried to find some mechanism to get the current machine’s NetBIOS domain name (the machine domain, not user domain), but couldn’t find anything in the usual places (e.g. System.Environment). If you want the fancy-schmancy Active Directory DNS domain then you can use Domain.GetComputerDomain().Name from System.DirectoryServices.ActiveDirectory, or another one that I stumbled across in Reflector was IPGlobalProperties.GetIPGlobalProperties().DomainName that lives in System.Net.NetworkInformation. But a simple way of getting the old-skool NetBIOS/LanManager-style machine domain name proved elusive.
Some googling suggested that WMI would provide the answer but I find WMI a little heavyweight, and not always reliable. The information is also probably in the registry somewhere, although I couldn’t find it after a cursory scan. The proper, supported way it would appear is to use the Network Management API. So my solution entailed P/Invoking to netapi32.dll.
If you’re after the same information I hope you find the code below useful. Once you’ve incorporated this in your project, just call the GetMachineNetBiosDomain method. It will return the machine’s Workgroup name if the machine is not domain-joined.
UPDATE: Now works on 64-bit thanks to update sent by Rp Brongers.
using System;
using System.Runtime.InteropServices;
using System.ComponentModel;
class NetUtil
{
[DllImport("netapi32.dll", CharSet = CharSet.Auto)]
static extern int NetWkstaGetInfo(string server,
int level,
out IntPtr info);
[DllImport("netapi32.dll")]
static extern int NetApiBufferFree(IntPtr pBuf);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
class WKSTA_INFO_100
{
public int wki100_platform_id;
[MarshalAs(UnmanagedType.LPWStr)]
public string wki100_computername;
[MarshalAs(UnmanagedType.LPWStr)]
public string wki100_langroup;
public int wki100_ver_major;
public int wki100_ver_minor;
}
public static string GetMachineNetBiosDomain()
{
IntPtr pBuffer = IntPtr.Zero;
WKSTA_INFO_100 info;
int retval = NetWkstaGetInfo(null, 100, out pBuffer);
if (retval != 0)
throw new Win32Exception(retval);
info = (WKSTA_INFO_100)Marshal.PtrToStructure(pBuffer, typeof(WKSTA_INFO_100));
string domainName = info.wki100_langroup;
NetApiBufferFree(pBuffer);
return domainName;
}
}

