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/

casperOne
  • 73,706
  • 19
  • 184
  • 253
BuddyJoe
  • 69,735
  • 114
  • 291
  • 466

3 Answers3

4

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
  • 524,688
  • 99
  • 697
  • 795
  • 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. – BuddyJoe Jun 17 '10 at 22:16
  • 1
    Has something to do with the IPv6 stack. http://stackoverflow.com/questions/1726585 – BuddyJoe Jun 17 '10 at 22:25
  • 1
    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 – BuddyJoe Jun 17 '10 at 22:27
2

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
  • 24,791
  • 9
  • 70
  • 92
  • 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) – BuddyJoe Jun 17 '10 at 22:21
0

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
  • 39,849
  • 11
  • 94
  • 127
  • 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. – BuddyJoe Jun 17 '10 at 22:23