Get the real IP of the client with ColdFusion

On 9 de outubro de 2014, in CFML, by andersonstraube

The simplest way to know the visitor’s IP address is:

<cfset ip = CGI.REMOTE_ADDR />

But this solution is not 100% accurate because if the client is using a proxy IP is obtained from the proxy server and not the address of the visitor, as if your system is in a cluster with load balance in front of the REMOTE_ADDR will return the balance of the IP and not the actual address of the client.

To solve this problem we can analyze the HTTP header which has a property that stores the original IP whose name is “X-Forwarded-For”. Some cases it returns more than one IP, in the case of using load balance and another proxy in front, so we always got the last IP that will certainly have a more precise result:

<cffunction name="getClientIP" access="public" output="false" returntype="string">

	<cfset var clientIP = "" />

		<cfif StructKeyExists(GetHttpRequestData().headers, "X-FORWARDED-FOR") >
			<cfset clientIP = GetHttpRequestData().headers["X-FORWARDED-FOR"] />

			<!--- If more than one IP in the case of using a public IP proxy is always the last value --->
			<cfif ListLen( clientIP ) gt 1 >
				<cfset clientIP = ListGetAt( clientIP, ListLen( clientIP ) ) />

			<cfset clientIP = Trim(clientIP) />
			<cfset clientIP = CGI.REMOTE_ADDR />

		<cfcatch type="any">
			<cfreturn "" />

	<cfreturn clientIP />

A hug, until the next.

Tagged with:  

Deixe uma resposta

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *