0

I want to show the IP address of the computer's client. But in my computer which running in localhost show only "::1" . If i run in the localhost, it should be show 127.0.0.1. So how to show the IP address especially in IPv4. Because I read in another article that the ::1 is in IPv6. Here is my code :

function get_ip()
{
    if (!empty($_SERVER['HTTP_CLIENT_IP']))   //check ip from share internet
    {
      $ip=$_SERVER['HTTP_CLIENT_IP'];
    }
    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   //to check ip is pass from proxy
    {
      $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    else
    {
      $ip=$_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}

$ip = get_ip(); 

echo $ip;

Give me help to fix this. Thank You.

dinda
  • 19
  • 2
  • 8

2 Answers2

1

If you want the web server to see you connecting from 127.0.0.1 then you must connect via IPv4. Try navigating to http://127.0.0.1 instead of http://localhost. If you are connecting via IPv6 then of course the web server will report an IPv6 address.

cdhowie
  • 158,093
  • 24
  • 286
  • 300
  • 1
    @dinda If you connect to the server via IPv6, then **IPv4 is not involved in the connection at all** and displaying the client's IPv4 address makes no sense because, from the server's perspective, **the client does not have an IPv4 address**. If you want to make "localhost" refer to 127.0.0.1 then you will need to edit your hosts file and remove "::1" from the "localhost" definition. – cdhowie Jun 25 '12 at 19:20
  • how to edit my hosts file and remove the ::1 from the localhost definition? Sorry for asking too much because I'm newbie. Thank You. – dinda Jun 25 '12 at 19:27
  • how to edit my hosts file and remove the ::1 from the localhost definition? Sorry for asking too much because I'm newbie. Thank You. – dinda Jun 25 '12 at 19:28
  • That's not really a stackoverflow question. Try googling your question and if you can't find the answer then ask on [superuser.com](http://superuser.com). – cdhowie Jun 27 '12 at 16:05
0
function getIP() {
    $ip = $_SERVER['SERVER_ADDR'];

    if (PHP_OS == 'WINNT'){
        $ip = getHostByName(getHostName());
    }

    if (PHP_OS == 'Linux'){
        $command="/sbin/ifconfig";
        exec($command, $output);

        $pattern = '/inet addr:?([^ ]+)/';

        $ip = array();
        foreach ($output as $key => $subject) {
            $result = preg_match_all($pattern, $subject, $subpattern);
            if ($result == 1) {
                if ($subpattern[1][0] != "127.0.0.1")
                $ip = $subpattern[1][0];
            }

        }
    }

    return $ip;
}

echo getIP();
Alex M
  • 2,756
  • 7
  • 29
  • 35