How to retrieve a visitor’s IP address

by admin on July 24, 2009 · 0 comments

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, 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.

Here it is 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 the 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 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

Previous post:

Next post: