Skip to content

Instantly share code, notes, and snippets.

@ghidinelli
Created September 13, 2015 23:20
Show Gist options
  • Select an option

  • Save ghidinelli/e01b83b6a2e628c17cd5 to your computer and use it in GitHub Desktop.

Select an option

Save ghidinelli/e01b83b6a2e628c17cd5 to your computer and use it in GitHub Desktop.
getRemoteAddress() for ColdFusion with or without common load balancers/firewalls
<cffunction name="getRemoteAddress" output="false" access="public" returntype="string" hint="Identify the remote user IP address">
<cfset var pc = getHTTPRequestData().headers />
<cfset var arrIP = "" />
<cfif structKeyExists(pc, "X-Forwarded-For") AND len(pc["X-Forwarded-For"])>
<!--- the x-forwarded-for header sometimes includes values that are too long like "172.27.156.64, 67.98.222.16". The regexp picks out just the matches. http://support.f5.com/kb/en-us/solutions/public/12000/200/sol12264.html --->
<cfset arrIP = reMatch('\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b', pc["X-Forwarded-For"]) />
<cfif arrayLen(arrIP)>
<cfreturn arrIP[1] />
<cfelse>
<cfreturn CGI.remote_addr />
</cfif>
<cfelse>
<cfreturn CGI.remote_addr />
</cfif>
</cffunction>
@ghidinelli
Copy link
Copy Markdown
Author

The regexp was pilfered from StackOverflow IIRC

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment