tags:

views:

2560

answers:

4

How can you get the FQDN of a local machine in C#?

+12  A: 

NOTE: I think this solution only works in the .NET 2.0 (and above) frameworks.

using System;
using System.Net;

//...

public static string GetFQDN()
{
    string domainName = NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;
    string hostName = Dns.GetHostName();
    string fqdn = "";
    if (!hostName.Contains(domainName))
        fqdn = hostName + "." + domainName;
    else
        fqdn = hostName;

    return fqdn;
}
Miky Dinescu
+8  A: 

A slight simplification of Miky D's code

    public static string GetLocalhostFqdn()
    {
        var ipProperties = IPGlobalProperties.GetIPGlobalProperties();
        return string.Format("{0}.{1}", ipProperties.HostName, ipProperties.DomainName);
    }
Matt Z
+1  A: 

Here it is in PowerShell, for the heck of it:

$ipProperties = [System.Net.NetworkInformation.IPGlobalProperties]::GetIPGlobalProperties()
"{0}.{1}" -f $ipProperties.HostName, $ipProperties.DomainName
halr9000
+1  A: 

And for Framework 1.1 is as simple as this:

System.Net.Dns.GetHostByName("localhost").HostName

And then remove de machine NETBIOS name to retrieve only the domainName

javizcaino