Patrick
Patrick

Reputation: 2577

Get the real ip address of a user with coldfusion

The only variables I found relating to a user's IP were the following:

<cfif #CGI.HTTP_X_Forwarded_For# EQ "">
    <CFSET ipaddress="#CGI.Remote_Addr#">
<cfelse>
    <CFSET ipaddress="#CGI.HTTP_X_Forwarded_For#">
</cfif>

Are there any other ways to check for a real ip address in coldfusion ?

Upvotes: 7

Views: 6600

Answers (1)

Kevin Morris
Kevin Morris

Reputation: 354

The code you have is already doing a decent job looking for the "best known" client IP address. Here is the over engineered code I use in my projects:

public string function getClientIp() {
    local.response = "";

    try {
        try {
            local.headers = getHttpRequestData().headers;
            if (structKeyExists(local.headers, "X-Forwarded-For") && len(local.headers["X-Forwarded-For"]) > 0) {
                local.response = trim(listFirst(local.headers["X-Forwarded-For"]));
            }
        } catch (any e) {}

        if (len(local.response) == 0) {
            if (structKeyExists(cgi, "remote_addr") && len(cgi.remote_addr) > 0) {
                local.response = cgi.remote_addr;
            } else if (structKeyExists(cgi, "remote_host") && len(cgi.remote_host) > 0) {
                local.response = cgi.remote_host;
            }
        }
    } catch (any e) {}

    return local.response;
}

Upvotes: 6

Related Questions