2011年9月19日 星期一

How to detect a visitor's IP address

Every visitor to your site or web application has an IP address. It is quite handy to be able to get that address. It can be used for security logging, or perhaps tracing. It can also be used to determine where they are in the world, or at least where their ISP is.
The difficulty is when they're behind a proxy of some sort, you only see the IP address of the proxy server. So, here are the code snippets in PHP,JSP, ASP and .Net that first check for an IP addresses that's forwarded from behind a proxy, and if there's none then just get the IP address.
  • PHP without Proxy detection
    <? $ipaddress = getenv(REMOTE_ADDR); ?>
  • PHP with Proxy detection
    <?if (getenv(HTTP_X_FORWARDED_FOR)) {
    $ipaddress = getenv(HTTP_X_FORWARDED_FOR);
    } else {
    $ipaddress = getenv(REMOTE_ADDR); }
    ?>
  • ASP without Proxy detection
    <%
    ipaddress = Request.ServerVariables("REMOTE_ADDR")
    %>
  • ASP with Proxy detection
    <%
    ipaddress = Request.ServerVariables("HTTP_X_FORWARDED_FOR")
    if ipaddress = "" then
    ipaddress = Request.ServerVariables("REMOTE_ADDR")
    end if
    %>
  • JSP without Proxy detection
    <%
    String ipaddress = request.getRemoteAddr();
    %>
  • JSP with Proxy detection
    <%
    if (request.getHeader("HTTP_X_FORWARDED_FOR") == null) {
    String ipaddress = request.getRemoteAddr();
    } else {
    String ipaddress = request.getHeader("HTTP_X_FORWARDED_FOR");
    }
    %>
我想了解如何获得IP地址的客户端,即访问我的网页。
内容的JSP页面:
<%  
out.print( request.getRemoteAddr() + "<br>"); 
out.print( request.getRemoteHost() );  
%> 
输出:
0:0:0:0:0:0:0:1 
0:0:0:0:0:0:0:1 

沒有留言:

張貼留言