59

I need to get the host name currently running the application. Any idea?

peterh
  • 11,875
  • 18
  • 85
  • 108
Beginner_Pal
  • 1,285
  • 6
  • 18
  • 23

5 Answers5

99

Something to bear in mind is that System.Environment.MachineName; and System.Windows.Forms.SystemInformation.ComputerName; will give you the NETBIOS name of the machine (restricted to 15 characters).

If you want the full TCP/IP based host name you can use Dns.GetHostName():

string hostName = System.Net.Dns.GetHostName();

Or you can use:

System.Environment.GetEnvironmentVariable("COMPUTERNAME");

Which will return the full computer name set during installation.

djdd87
  • 67,346
  • 27
  • 156
  • 195
  • 3
    Well, the docs are a bit vague on how it's implemented, but it is implied that it requires a) a working network connection, b) a round-trip to the DNS server, and c) that the DNS actually knows your machine name (it doesn't have to, unless your a server) – James Curran Aug 16 '10 at 16:09
  • 1
    @James Curran - Absolutely. But Environment.MachineName restricts the computer name to a 15 character NETBIOS name. GetHostName will retrieve the full TCP/IP based hostname. – djdd87 Aug 16 '10 at 16:21
  • 5
    `System.Environment.GetEnvironmentVariable("COMPUTERNAME");` is Windows only – gman Jan 28 '16 at 03:10
  • Will this still work if the code is running on IIS? What will it return? something like "www.mySiteAddress.com" ?? – AleX_ Aug 04 '17 at 19:42
35

Unless I am mistaken on what you want to do..

System.Environment.MachineName
Wil
  • 2,328
  • 2
  • 20
  • 27
10

To get fully qualified name, use:

 System.Net.Dns.GetHostEntry("").HostName
Dynamic
  • 1,553
  • 2
  • 19
  • 25
4

The My namespace contains many great "helper" functions like:

My.Computer.Name
Nathan
  • 431
  • 2
  • 10
2
System.Windows.Forms.SystemInformation.ComputerName;
Nobody
  • 4,731
  • 7
  • 36
  • 65
  • 1
    Looks like this one also gets the NetBIOS name, so the same as `System.Environment.MachineName` and avoiding a potentially awkward System.Windows.Forms situation. – Jonas Aug 16 '22 at 11:47