开发者

How to detect if running on localhost

I have a PHP script where I'd like to detect if the user is running on a local machine, not accessible over the In开发者_如何学编程ternet. Currently I check for the server address to he 127.0.0.1. Is this the best practice or is there a better way?


Localhost always translates to the loopback IP address 127.0.0.1 in IPv4, or ::1 in IPv6, So validating the IP Within your application would be secure, if you mean

if(IPAddress::In(array("127.0.0.1","::1")))
{
     //Show Application
}

I Very much doubt that you will have a team of elite hackers after your port 80 but as a side note there has been some talk about flaws in relying on an IP address as TCP Packets can be modified.

But that should not be a worry for you.


I'm not sure the answers so far are on point, but it may be me that's confused. I'm responding in particular to the part of your question that says, "not accessible over the Internet". Here's my attempt at an answer:

The web server, not PHP, listens on a socket and accepts connections. PHP can get information about the connection from $_SERVER (http://www.php.net/manual/en/reserved.variables.server.php). Be aware that all you're checking is from whence the connection came - you can't learn anything about whether your server is available via other IP addresses from $_SERVER. For example, I can access my local instance of Apache/PHP via any of:

  • http://localhost/ ($_SERVER["SERVER_ADDR"] => ::1)
  • http://127.0.0.1/ ($_SERVER["SERVER_ADDR"] => 127.0.0.1)
  • http://192.168.75.121/ ($_SERVER["SERVER_ADDR"] => 192.168.75.121)
  • http://shiva.local/ ($_SERVER["SERVER_ADDR"] => fe80::21c:42ff:fe00:8)

So, if your plan is that the app is to behave differently upon seeing the "correct" value in $_SERVER["SERVER_ADDR"], you're probably pretty safe - i.e., it's unlikely that could be spoofed by a user from a remote client.

Having said all of that, I would not use any of these techniques for either authentication of users or authorization of user privileges/actions on a deployed application that is available over the Internet. The one exception might be if you've got an entire app that is only to be available when accessed from localhost - then this technique probably makes decent sense and will be secure enough for a personal app.


You can also check the hostname localhost but if the server address is 127.0.0.1 then it should resolve. This is standard practice on ipv4. On ipv6 you are able to check ::1 as Robert Pitt suggests.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜