Different Ways to Get the Server Name in Asp. Net

I want to log my server name in ASP.NET Application, I use multi-servers and load balancing so I need to log the server name.

But what is the difference between these ways to get the server name?

and which one is true or better to log?

any idea?

or any other ways?

System.Environment.MachineName
Server.MachineName
System.Net.Dns.GetHostName()

There is also another ways but not always return correct server name:

Request.ServerVariables["SERVER_NAME"]
System.Net.Dns.GetHostEntry(Request.ServerVariables("SERVER_NAME")).HostName
System.Net.Dns.GetHostEntry(Request.ServerVariables("LOCAL_ADDR")).HostName
1

2 Answers

I know this is an old question. I was searching for answer to the same issue; here is my solution.

string url = HttpContext.Current.Request.Url.ToString();
string[] tempArray = url.Split('/');
string serverName = tempArray[0] + "/" + tempArray[1] + "/" + tempArray[2] ;

This way you will get the exact server name.

3

I always prefer simple and fail-safe solutions. I suggest to add an application setting to the application web.config and populate it with the desired name for each server manually.

<appSettings>
  <add key="ServerName" value="Server_1" />
</appSettings>

you can read this setting later:

string serverName = ConfigurationSettings.AppSettings["ServerName"];

This way you will gain full manual control on your server names.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Sophia Al-Mansoor

Sophia Al-Mansoor

Global Business & E-Commerce Reporter

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.

Share this article
Twitter Facebook Pinterest