How to get original visitor IP from Cloudflare

by 0

Clouldflare use header params:  HTTP_CF_CONNECTING_IP to provide original IP




IN PHP


$ip = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];


In .net

C#

protected string GetIPAddress()
{
    System.Web.HttpContext context = System.Web.HttpContext.Current; 
    string ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

    if (!string.IsNullOrEmpty(ipAddress))
    {
        string[] addresses = ipAddress.Split(',');
        if (addresses.Length != 0)
        {
            return addresses[0];
        }
    }

    return context.Request.ServerVariables["HTTP_CF_CONNECTING_IP"];
}

VB.net

Public Shared Function GetIPAddress() As String
    Dim context As System.Web.HttpContext = System.Web.HttpContext.Current
    Dim sIPAddress As String = context.Request.ServerVariables("HTTP_X_FORWARDED_FOR")
    If String.IsNullOrEmpty(sIPAddress) Then
        Return context.Request.ServerVariables("HTTP_CF_CONNECTING_IP")    Else
        Dim ipArray As String() = sIPAddress.Split(New [Char]() {","c})
        Return ipArray(0)
    End If
End Function



For everyone use PHPBB and Cloudflare:

1. edit includes/session.php
2. at ~ line 270
find:
$this->ip = (!empty($_SERVER['REMOTE_ADDR'])) ? htmlspecialchars((string) $_SERVER['REMOTE_ADDR']) : '';

replace with:
$this->ip = (!empty($_SERVER['HTTP_CF_CONNECTING_IP'])) ? htmlspecialchars((string) $_SERVER['HTTP_CF_CONNECTING_IP']) : '';

Leave a Reply