https://moxiaomo0804.slack.com/archives/D0563NXT248/p1684154802789179

php
$ip        = $_SERVER['REMOTE_ADDR'] ?? null;
$forwarded = $_SERVER['HTTP_X_FORWARDED_FOR'] ?? null;  
$client_ip = $_SERVER['HTTP_CLIENT_IP'] ?? null;

if ($forwarded) {
    $ips = explode(',', $forwarded);
    foreach ($ips as $ip) {
        if (!preg_match('/^(10|172\.16|192\.168)\./', $ip)) {
            $ip = $ip;
            break; 
        }
    }
}

$ip_versions = [
    '4' => 'FILTER_VALIDATE_IP', 
    '6' => 'FILTER_VALIDATE_IP', 
];

foreach ($ip_versions as $version => $filter) {
    $ip_filtered = filter_var($ip, $filter, FILTER_FLAG_IPV$version);
    if ($ip_filtered) {
        $ip         = $ip_filtered;
        $ip_version = $version;
        break;
    }
}

if (empty($ip_version)) {
    $ip       = '未知';
    $ip_version = ''; 
}

echo "IP地址: $ip<br>IP版本: IPv$ip_version";

作者 meiyoufan

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注