asp.net.netrequest.servervariables

ASP.NET - Telling the difference between localhost and 127.0.0.1


How can you tell the difference between a request going to 127.0.0.1 and localhost.

This line of code on Windows 7 and VS2010 built-in web server can not tell the difference.

if (Request.ServerVariables["SERVER_NAME"].ToLower() == "localhost")
{

}

try hitting your own built-in web server with: http://127.0.0.1/ and then http://localhost/


Solution

  • Request.Headers will differentiate the requests:

    if (Request.Headers["host"].ToLower() == "localhost") 
    { 
      //shouldn't be hit for 127.0.0.1
    } 
    

    Note: depending on your needs, you will have to consider clearing off the port number before your check.