How to get server domain name How to get server domain name asp.net asp.net

How to get server domain name


You'll need to extract it from the request object:

HttpContext.Current.Request.Url.Host


If anyone here is actually searching for the domain name of the server, here is a hack I've been using since the .Net beginnings:

    [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;    }

You can actually grab a bit of info from there. Update: Now works with 64 bit.

Thanks Duncan for the 64bit version.


A bit late.. But the missing and best answer I have found, after having exactly the same issue:

private static string getComputerDomain()        {            try            {                return Domain.GetComputerDomain().Name;            }            catch (ActiveDirectoryObjectNotFoundException)            {                return "Local (No domain)";            }        }

As stated on the msdn site:

This return value is independent of the domain credentials under which the application is run. This method will retrieve the computer's domain regardless of the trusted account domain credentials it is run under.

Tested on my personal pc (no AD-domain) and at work (with AD-domain) under IIS (anonymous access).