views:

63

answers:

3

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/

+3  A: 

Does it matter? Don't you just want to know if the connection is a local connection? I would just use the IsLocal property for this.

if (Request.IsLocal)
{
}
tvanfosson
actually it does. The built-in DNS localhost resolution in Windows 7 is horrible. Uncommenting the line in the hosts file doesn't seem to help. And I need to hit 127.0.0.1 instead of localhost or its dead slow. Every single request wastes time resolving the DNS. On an ajax heavy app this is terrible.
tyndall
Has something to do with the IPv6 stack. http://stackoverflow.com/questions/1726585
tyndall
Maybe it is Firefox issue, and I can use one of those fixes. But I still wanted to know how to bypass the DNS with 127.0.0.1. Nice point about the IsLocal though +1
tyndall
A: 

You can actually specify any name as your localhost Server Name (just edit your hosts file for example, and use an arbitrary name)

You probably want to let the machine tell you if it's a local request rather than trying to figure it out for yourself.

John Weldon
see comments - will have to check the speed of just picking random name and puttng it into hosts. I have done this on other OSes before but not Windows 7 before.
tyndall
+2  A: 

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.

jball
That or HTTP_HOST will do the trick. This is great. Will help me avoid the issue that I am seeing. (see comment to tvanfosson)
tyndall