How to detect a visitor’s IP address

How to detect a visitor’s IP address

    Every visitor to your site or web application has an IP address. It can be used to determine where they are in the world, or at least where their ISP is.
You know that when users are behind any routers or proxies the REMOTE_ADDR returns the IP Address of the router and not the client user’s machine. We need check HTTP_X_FORWARDED_FOR, since when client user is behind a proxy server its machine’s IP Address and Proxy Server’s IP Address is appended to the client machine’s IP Address. So, we need to check HTTP_X_FORWARDED_FOR and then REMOTE_ADDR.

So, here are the sample codes in PHP, ASP , JSP, C# 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.

Here it is how to get IP address in PHP


<?
    if (getenv(HTTP_X_FORWARDED_FOR)) { 
        $ip_address = getenv(HTTP_X_FORWARDED_FOR); 
    } else { 
        $ip_address = getenv(REMOTE_ADDR);
    }
?>

And here’s how to get IP address in ASP


<%
    ip_address = Request.ServerVariables("HTTP_X_FORWARDED_FOR")
    if ip_address = "" then
        ip_address = Request.ServerVariables("REMOTE_ADDR")
    end if
%>

And here’s how to get IP address in JSP


<%
    if (request.getHeader("HTTP_X_FORWARDED_FOR") == null) {
    String ipaddress = request.getRemoteAddr();
    } else {
    String ipaddress = request.getHeader("HTTP_X_FORWARDED_FOR");
    }
%>

And here’s the IP retriever with proxy detection in .Net (C#)


public string IpAddress()
{
    string strIpAddress;
    strIpAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
    if (strIpAddress == null)
    {
       strIpAddress = Request.ServerVariables["REMOTE_ADDR"];
    }
    return strIpAddress;
}

And here’s the same IP retriever with proxy detection in .Net, but in VB.Net


Public Function IpAddress()
    Dim strIpAddress As String
    strIpAddress = Request.ServerVariables("HTTP_X_FORWARDED_FOR")
    If strIpAddress = "" Then
       strIpAddress = Request.ServerVariables("REMOTE_ADDR")
    End If
    IpAddress = strIpAddress
End Function
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: