Get Real Ip Address

I’m ing this code to display the IP address.




<?php

function GetRealIPAddress()

{

    if (isset($_SERVER["HTTP_CLIENT_IP"]))

    {

        return $_SERVER["HTTP_CLIENT_IP"];

    }

    elseif (isset($_SERVER["HTTP_X_FORWARDED_FOR"]))

    {

        return $_SERVER["HTTP_X_FORWARDED_FOR"];

    }

    elseif (isset($_SERVER["HTTP_X_FORWARDED"]))

    {

        return $_SERVER["HTTP_X_FORWARDED"];

    }

    elseif (isset($_SERVER["HTTP_FORWARDED_FOR"]))

    {

        return $_SERVER["HTTP_FORWARDED_FOR"];

    }

    elseif (isset($_SERVER["HTTP_FORWARDED"]))

    {

        return $_SERVER["HTTP_FORWARDED"];

    }

    else

    {

        return $_SERVER["REMOTE_ADDR"];

    }

}

echo GetRealIPAddress();

?>



But it show like this.




::1



How can i get my real ip?

I believe that what you’re seeing is the IPV6 version of localhost. I suspect that it will work once you’re logging in from a different machine.

Just checked and confirmed here.

How we can access the public IP address?

You shouldn’t need to, the public IP will appear when you’re not connecting from the dev machine.

If you need to see what’s available, try seeing what’s held in the $_SERVER array:




print_r($_SERVER);



I’m using this in my config:




/**

 * Get client IP address

 * @return string

 */

function getIpAddress() {

	foreach (array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR') as $key) {

		if (array_key_exists($key, $_SERVER) === true) {

			foreach (explode(',', $_SERVER[$key]) as $ip) {

				$ip = trim($ip);

				if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false) {

					return $ip;

				}

			}

		}

	}

}




// client IP address

$ip = getIpAddress();

$ip = (is_null($ip)) ? '' : $ip;



You don’t seem to understand so I’ll re-iterate a previous comment.

::1 is being returned because you are connecting to your local machine (localhost).

When you deploy the application to a remote web server, your real IP will be returned.

If you wish to do some testing (geoip or something similar), then check if the IP = ::1 and set it to your real ip.


if ($ip == '::1') {

 $ip = '123.456.789.123'; // enter your real IP address here

}

Your real IP can easily be found by Googling "what is my ip address".

Thanks to all replys

Here is my non intrusive implementation.

  1. You will test it like this. In any Controller action, add:

echo '<pre>'; print_r(Yii::app()->request->getUserHostAddress()); exit(0);

  1. in protected/config/main.php, under the components section add:



        'request'=>array( 

            'class' => 'NTDI_CHttpRequest',

        ),



this will tell Yii Fw to use the new NTDI_CHttpRequest class instead the core CHttpRequest class when dealing with Http Request.

  1. in protected/components/ make a new file with the same name as the new class name .php

    NTDI_CHttpRequest.php file:




<?php


interface HttpRequestable {

    public function getUserHostAddress();

}


/**

 * NTDI_CHttpRequest offers an improved version of the CHttpRequest::getUserHostAddress()

 * The method, is a port from Codeigniter w some small mods.

 * 

 * If your server is behind a reverse proxy, you must whitelist the proxy IP

 * addresses the Framework should trust the HTTP_X_FORWARDED_FOR

 * header in order to properly identify the visitor's IP address.

 * 

 * @author p0pemar1naru

 */

class NTDI_CHttpRequest extends CHttpRequest implements HttpRequestable {


    /**

     * Reverse Proxy IPs.

     * @var string Comma-delimited, e.g. '10.0.1.200,10.0.1.201'

     */

    protected $ntdi_proxyIP = '';


    /**

     * IP address of the current user

     * @var boolean

     */

    private $ntdi_IPAddress = FALSE;


    public function init()

    {

        parent::init();

    }


    /**

     * Fetch the IP Address. Determines and validates the visitor's IP address.

     * @return string IP address

     */

    public function getUserHostAddress()

    {

        if ($this->ntdi_IPAddress !== FALSE)

            return $this->ntdi_IPAddress;

        if ($this->ntdi_proxyIP != '' && isset($_SERVER['HTTP_X_FORWARDED_FOR']) && isset($_SERVER['REMOTE_ADDR'])) {

            $proxies = preg_split('/[\s,]/', $this->ntdi_proxyIP, -1, PREG_SPLIT_NO_EMPTY);

            $proxies = is_array($proxies) ? $proxies : array($proxies);

            $this->ntdi_IPAddress = in_array($_SERVER['REMOTE_ADDR'], $proxies) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];

        } elseif (isset($_SERVER['REMOTE_ADDR']) && isset($_SERVER['HTTP_CLIENT_IP']))

            $this->ntdi_IPAddress = $_SERVER['HTTP_CLIENT_IP'];

        elseif (isset($_SERVER['REMOTE_ADDR']))

            $this->ntdi_IPAddress = $_SERVER['REMOTE_ADDR'];

        elseif (isset($_SERVER['HTTP_CLIENT_IP']))

            $this->ntdi_IPAddress = $_SERVER['HTTP_CLIENT_IP'];

        elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR']))

            $this->ntdi_IPAddress = $_SERVER['HTTP_X_FORWARDED_FOR'];


        if ($this->ntdi_IPAddress === FALSE) {

            $this->ntdi_IPAddress = '0.0.0.0';

            return $this->ntdi_IPAddress;

        }

        if (strpos($this->ntdi_IPAddress, ',') !== FALSE) {

            $x = explode(',', $this->ntdi_IPAddress);

            $this->ntdi_IPAddress = trim(end($x));

        }

        if (!$this->ntdi_isValidIP($this->ntdi_IPAddress))

            $this->ntdi_IPAddress = '0.0.0.0';

        return $this->ntdi_IPAddress;

    }


    /**

     * Validate IP Address

     * @param string $ip

     * @return boolean

     */

    public function ntdi_isValidIP($ip)

    {

        $ip_segments = explode('.', $ip);

        // Always 4 segments needed

        if (count($ip_segments) != 4)

            return FALSE;

        // IP can not start with 0

        if ($ip_segments[0][0] == '0')

            return FALSE;

        // Check each segment

        foreach ($ip_segments as $segment) {

            // IP segments must be digits and can not be

            // longer than 3 digits or greater then 255

            if ($segment == '' || preg_match("/[^0-9]/", $segment) || $segment > 255 || strlen($segment) > 3)

                return FALSE;

        }

        return TRUE;

    }


}




NOTE: the role of the interface is to give me a clear understanding of what method was overriden from core class.