简体   繁体   中英

IPv4 address with PHP

I want to get the IPv4 address, but not the localhost address (127.0.0.1). I just get ::1.

i tried it with $ip = getenv ("REMOTE_ADDR");

and

$ip = getenv ('SERVER_ADDR');
$ip = $_SERVER['REMOTE_ADDR'];

Finally i got the answer at the same day. You can see it below:

    function getIP() {
    $ip = $_SERVER['SERVER_ADDR'];

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

    if (PHP_OS == 'Linux'){
        $command="/sbin/ifconfig";
        exec($command, $output);
        // var_dump($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];
            }
        //var_dump($subpattern);
        }
    }
    return $ip;
}

您可以使用gethostbyname()获得 IPv4 地址,例如使用gethostbyname($_SERVER['HTTP_HOST'])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM