How to detect if running on localhost

青春壹個敷衍的年華 提交于 2019-12-21 04:21:14

问题


I have a PHP script where I'd like to detect if the user is running on a local machine, not accessible over the Internet. Currently I check for the server address to he 127.0.0.1. Is this the best practice or is there a better way?


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/4573021/how-to-detect-if-running-on-localhost

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!