什么是最准确的方式来检索用户在PHP中的正确的IP地址?

我知道有许多$ _SERVERvariables头可用于IP地址检索。 我想知道是否有一个普遍的共识,如何最准确地检索用户的真实IP地址(知道没有方法是完美的)使用上述variables?

我花了一些时间试图find一个深入的解决scheme,并提出了基于一些来源的以下代码。 如果有人能够在答案中找出答案,或者对可能更准确的东西进行阐述,我会喜欢它。

编辑包含来自@Alix的优化

/** * Retrieves the best guess of the client's actual IP address. * Takes into account numerous HTTP proxy headers due to variations * in how different ISPs handle IP addresses in headers between hops. */ public function get_ip_address() { // Check for shared internet/ISP IP if (!empty($_SERVER['HTTP_CLIENT_IP']) && $this->validate_ip($_SERVER['HTTP_CLIENT_IP'])) return $_SERVER['HTTP_CLIENT_IP']; // Check for IPs passing through proxies if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { // Check if multiple IP addresses exist in var $iplist = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']); foreach ($iplist as $ip) { if ($this->validate_ip($ip)) return $ip; } } } if (!empty($_SERVER['HTTP_X_FORWARDED']) && $this->validate_ip($_SERVER['HTTP_X_FORWARDED'])) return $_SERVER['HTTP_X_FORWARDED']; if (!empty($_SERVER['HTTP_X_CLUSTER_CLIENT_IP']) && $this->validate_ip($_SERVER['HTTP_X_CLUSTER_CLIENT_IP'])) return $_SERVER['HTTP_X_CLUSTER_CLIENT_IP']; if (!empty($_SERVER['HTTP_FORWARDED_FOR']) && $this->validate_ip($_SERVER['HTTP_FORWARDED_FOR'])) return $_SERVER['HTTP_FORWARDED_FOR']; if (!empty($_SERVER['HTTP_FORWARDED']) && $this->validate_ip($_SERVER['HTTP_FORWARDED'])) return $_SERVER['HTTP_FORWARDED']; // Return unreliable IP address since all else failed return $_SERVER['REMOTE_ADDR']; } /** * Ensures an IP address is both a valid IP address and does not fall within * a private network range. * * @access public * @param string $ip */ public function validate_ip($ip) { if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_IPV6 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false) return false; self::$ip = $ip; return true; } 

警告词(更新)

REMOTE_ADDR仍然是IP地址最可靠的来源。 这里提到的其他$_SERVERvariables很容易被远程客户端欺骗。 此解决scheme的目的是尝试确定代理服务器后面的客户端的IP地址。 为了您的一般目的,您可以考虑将其与从$_SERVER['REMOTE_ADDR']直接返回的IP地址结合使用并同时存储。

对于99.9%的用户来说,这个解决scheme将完美地满足您的需求。 它不会保护你免受0.1%的恶意用户的注意,通过注入他们自己的请求头来滥用你的系统。 如果依靠IP地址执行关键任务,请使用REMOTE_ADDR而不要打扰代理服务器后面的用户。

这是一个更简洁,更清晰的IP地址获取方式:

 function get_ip_address(){ 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); // just to be safe if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false){ return $ip; } } } } } 

我希望它有帮助!


你的代码似乎已经相当完整了,我看不到任何可能的错误(除了通常的IP警告),我会改变validate_ip()函数来依靠filter扩展:

 public function validate_ip($ip) { if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false) { return false; } self::$ip = sprintf('%u', ip2long($ip)); // you seem to want this return true; } 

此外,您的HTTP_X_FORWARDED_FOR片段可以简化为:

 // check for IPs passing through proxies if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { // check if multiple ips exist in var if (strpos($_SERVER['HTTP_X_FORWARDED_FOR'], ',') !== false) { $iplist = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']); foreach ($iplist as $ip) { if ($this->validate_ip($ip)) return $ip; } } else { if ($this->validate_ip($_SERVER['HTTP_X_FORWARDED_FOR'])) return $_SERVER['HTTP_X_FORWARDED_FOR']; } } 

对此:

 // check for IPs passing through proxies if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { $iplist = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']); foreach ($iplist as $ip) { if ($this->validate_ip($ip)) return $ip; } } 

您可能还想要validationIPv6地址。

但即使如此,获取用户的真实IP地址也是不可靠的。 他们所需要做的就是使用匿名代理服务器(不遵循http_x_forwarded_for,http_forwarded等的标头),并且获得的只是代理服务器的IP地址。

然后,您可以查看是否存在匿名的代理服务器IP地址列表,但是无法确定该代理服务器的IP地址是否100%准确,并且最多只能让您知道它是代理服务器。 如果有人很聪明,他们可以欺骗HTTP转发头。

假设我不喜欢当地的大学。 我弄清楚他们注册了哪些IP地址,并通过做坏事取得他们在你的网站上禁止的IP地址,因为我知道你尊重HTTP转发。 名单是无止境的。

然后,就像你猜测的那样,内部IP地址,比如我之前提到过的大学networking。 很多使用10.xxx格式。 所以你只知道它被转发了一个共享的networking。

那么我就不会太多入手,但dynamicIP地址已经成为宽带的一种方式了。 所以。 即使你得到一个用户的IP地址,预计它会在最长的2 – 3个月内改变。

我们用:

 /** * Get the customer's IP address. * * @return string */ public function getIpAddress() { if (!empty($_SERVER['HTTP_CLIENT_IP'])) { return $_SERVER['HTTP_CLIENT_IP']; } else if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ips = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']); return trim($ips[count($ips) - 1]); } else { return $_SERVER['REMOTE_ADDR']; } } 

HTTP_X_FORWARDED_FOR上的爆炸是因为我们在使用squid时检测到IP地址的奇怪问题。

最大的问题是为了什么目的?

您的代码几乎尽可能全面 – 但是我看到,如果您发现代理添加头像是什么,那么您使用CLIENT_IP的INSTEAD,但是如果您希望将此信息用于审计目的,那么请注意 – 它非常容易假货。

当然你不应该使用IP地址进行任何forms的authentication – 即使这些都可以被欺骗。

您可以通过推出一个通过非http端口连接到服务器的flash或java applet来更好地衡量客户端的ip地址(因此可以揭示透明的代理或者代理注入的头部是错误的情况 – 但请记住,如果客户端只能通过Web代理进行连接,或者输出端口被阻止,那么将不会有来自该小程序的连接。

C。

只是一个VB.NET版本的答案:

 Private Function GetRequestIpAddress() As IPAddress Dim serverVariables = HttpContext.Current.Request.ServerVariables Dim headersKeysToCheck = {"HTTP_CLIENT_IP", _ "HTTP_X_FORWARDED_FOR", _ "HTTP_X_FORWARDED", _ "HTTP_X_CLUSTER_CLIENT_IP", _ "HTTP_FORWARDED_FOR", _ "HTTP_FORWARDED", _ "REMOTE_ADDR"} For Each thisHeaderKey In headersKeysToCheck Dim thisValue = serverVariables.Item(thisHeaderKey) If thisValue IsNot Nothing Then Dim validAddress As IPAddress = Nothing If IPAddress.TryParse(thisValue, validAddress) Then Return validAddress End If End If Next Return Nothing End Function 

我意识到上面有更好更简洁的答案,这不是一个function,也不是最优美的脚本。 在我们的例子中,我们需要输出可伪造的x_forwarded_for和更可靠的remote_addr。 它需要允许空白注入其他函数,如果没有或如果单数(而不是只是返回预格式化函数)。 它需要一个“打开或closures”var与每个开关定制标签(S)平台设置。 它也需要一个方法来使$ ip根据请求是dynamic的,这样它就会以forwarded_for的forms出现。

我也没有看到任何人的地址isset()vs!empty() – 它可能为x_forwarded_forinput任何内容,但仍然触发isset()导致空白var的真相,一种方法是使用&&并将两者作为条件。 请记住,你可以欺骗“PWNED”这样的词作为x_forwarded_for,所以要确保你消毒到一个真正的IP语法,如果你输出的地方保护或DB。

此外,如果您需要使用多代理来查看x_forwarder_for中的数组,则可以使用google translate进行testing。 如果您想伪装标头进行testing,请查看Chrome Client Header Spoof扩展程序。 在匿名代理之后,这将默认为标准的remote_addr。

我不知道remote_addr可能是空的情况,但是为了以防万一。

 // proxybuster - attempts to un-hide originating IP if [reverse]proxy provides methods to do so $enableProxyBust = true; if (($enableProxyBust == true) && (isset($_SERVER['REMOTE_ADDR'])) && (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) && (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))) { $ip = end(array_values(array_filter(explode(',',$_SERVER['HTTP_X_FORWARDED_FOR'])))); $ipProxy = $_SERVER['REMOTE_ADDR']; $ipProxy_label = ' behind proxy '; } elseif (($enableProxyBust == true) && (isset($_SERVER['REMOTE_ADDR']))) { $ip = $_SERVER['REMOTE_ADDR']; $ipProxy = ''; $ipProxy_label = ' no proxy '; } elseif (($enableProxyBust == false) && (isset($_SERVER['REMOTE_ADDR']))) { $ip = $_SERVER['REMOTE_ADDR']; $ipProxy = ''; $ipProxy_label = ''; } else { $ip = ''; $ipProxy = ''; $ipProxy_label = ''; } 

为了使这些dynamic在下面的函数或查询/回显/视图中使用,说对于日志gen或错误报告,使用全局variables或只是在任何你想要的地方回声em,而不需要大量的其他条件或静态模式输出function。

 function fooNow() { global $ip, $ipProxy, $ipProxy_label; // begin this actions such as log, error, query, or report } 

谢谢你的所有伟大的想法。 请让我知道如果这可能会更好,仍然有点新的这些标题:)

我想出了这个函数不仅仅是返回IP地址,而是一个带有IP信息的数组。

 // Example usage: $info = ip_info(); if ( $info->proxy ) { echo 'Your IP is ' . $info->ip; } else { echo 'Your IP is ' . $info->ip . ' and your proxy is ' . $info->proxy_ip; } 

这个function:

 /** * Retrieves the best guess of the client's actual IP address. * Takes into account numerous HTTP proxy headers due to variations * in how different ISPs handle IP addresses in headers between hops. * * @since 1.1.3 * * @return object { * IP Address details * * string $ip The users IP address (might be spoofed, if $proxy is true) * bool $proxy True, if a proxy was detected * string $proxy_id The proxy-server IP address * } */ function ip_info() { $result = (object) array( 'ip' => $_SERVER['REMOTE_ADDR'], 'proxy' => false, 'proxy_ip' => '', ); /* * This code tries to bypass a proxy and get the actual IP address of * the visitor behind the proxy. * Warning: These values might be spoofed! */ $ip_fields = array( 'HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR', ); foreach ( $ip_fields 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_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE ) !== false ) { $forwarded = $ip; break 2; } } } } // If we found a different IP address then REMOTE_ADDR then it's a proxy! if ( $forwarded != $result->ip ) { $result->proxy = true; $result->proxy_ip = $result->ip; $result->ip = $forwarded; } return $result; } 

我想知道是否应该以相反的顺序迭代爆炸的HTTP_X_FORWARDED_FOR,因为我的经验是用户的IP地址在逗号分隔列表的末尾,所以从头部开始,更有可能获得返回的代理之一的IP地址,这可能仍然允许会话劫持,因为许多用户可能通过该代理。

感谢这个,非常有用。

如果代码在语法上是正确的,这将有所帮助。 因为在第20行有太多的内容。恐怕没有人真的试过这个。

我可能是疯了,但在几个有效和无效的地址尝试之后,validate_ip()工作的唯一版本是这样的:

  public function validate_ip($ip) { if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE) === false) return false; if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE) === false) return false; if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false && filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) === false) return false; return true; } 

如果您使用CloudFlarecaching层服务,则这是一个修改版本

 function getIP() { $fields = array('HTTP_X_FORWARDED_FOR', 'REMOTE_ADDR', 'HTTP_CF_CONNECTING_IP', 'HTTP_X_CLUSTER_CLIENT_IP'); foreach($fields as $f) { $tries = $_SERVER[$f]; if (empty($tries)) continue; $tries = explode(',',$tries); foreach($tries as $try) { $r = filter_var($try, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE); if ($r !== false) { return $try; } } } return false; } 

再一个干净的方法:

  function validateIp($var_ip){ $ip = trim($var_ip); return (!empty($ip) && $ip != '::1' && $ip != '127.0.0.1' && filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false) ? $ip : false; } function getClientIp() { $ip = @$this->validateIp($_SERVER['HTTP_CLIENT_IP']) ?: @$this->validateIp($_SERVER['HTTP_X_FORWARDED_FOR']) ?: @$this->validateIp($_SERVER['HTTP_X_FORWARDED']) ?: @$this->validateIp($_SERVER['HTTP_FORWARDED_FOR']) ?: @$this->validateIp($_SERVER['HTTP_FORWARDED']) ?: @$this->validateIp($_SERVER['REMOTE_ADDR']) ?: 'LOCAL OR UNKNOWN ACCESS'; return $ip; } 

从Symfony的请求类https://github.com/symfony/symfony/blob/1bd125ec4a01220878b3dbc3ec3156b073996af9/src/Symfony/Component/HttpFoundation/Request.php

 const HEADER_FORWARDED = 'forwarded'; const HEADER_CLIENT_IP = 'client_ip'; const HEADER_CLIENT_HOST = 'client_host'; const HEADER_CLIENT_PROTO = 'client_proto'; const HEADER_CLIENT_PORT = 'client_port'; /** * Names for headers that can be trusted when * using trusted proxies. * * The FORWARDED header is the standard as of rfc7239. * * The other headers are non-standard, but widely used * by popular reverse proxies (like Apache mod_proxy or Amazon EC2). */ protected static $trustedHeaders = array( self::HEADER_FORWARDED => 'FORWARDED', self::HEADER_CLIENT_IP => 'X_FORWARDED_FOR', self::HEADER_CLIENT_HOST => 'X_FORWARDED_HOST', self::HEADER_CLIENT_PROTO => 'X_FORWARDED_PROTO', self::HEADER_CLIENT_PORT => 'X_FORWARDED_PORT', ); /** * Returns the client IP addresses. * * In the returned array the most trusted IP address is first, and the * least trusted one last. The "real" client IP address is the last one, * but this is also the least trusted one. Trusted proxies are stripped. * * Use this method carefully; you should use getClientIp() instead. * * @return array The client IP addresses * * @see getClientIp() */ public function getClientIps() { $clientIps = array(); $ip = $this->server->get('REMOTE_ADDR'); if (!$this->isFromTrustedProxy()) { return array($ip); } if (self::$trustedHeaders[self::HEADER_FORWARDED] && $this->headers->has(self::$trustedHeaders[self::HEADER_FORWARDED])) { $forwardedHeader = $this->headers->get(self::$trustedHeaders[self::HEADER_FORWARDED]); preg_match_all('{(for)=("?\[?)([a-z0-9\.:_\-/]*)}', $forwardedHeader, $matches); $clientIps = $matches[3]; } elseif (self::$trustedHeaders[self::HEADER_CLIENT_IP] && $this->headers->has(self::$trustedHeaders[self::HEADER_CLIENT_IP])) { $clientIps = array_map('trim', explode(',', $this->headers->get(self::$trustedHeaders[self::HEADER_CLIENT_IP]))); } $clientIps[] = $ip; // Complete the IP chain with the IP the request actually came from $firstTrustedIp = null; foreach ($clientIps as $key => $clientIp) { // Remove port (unfortunately, it does happen) if (preg_match('{((?:\d+\.){3}\d+)\:\d+}', $clientIp, $match)) { $clientIps[$key] = $clientIp = $match[1]; } if (!filter_var($clientIp, FILTER_VALIDATE_IP)) { unset($clientIps[$key]); } if (IpUtils::checkIp($clientIp, self::$trustedProxies)) { unset($clientIps[$key]); // Fallback to this when the client IP falls into the range of trusted proxies if (null === $firstTrustedIp) { $firstTrustedIp = $clientIp; } } } // Now the IP chain contains only untrusted proxies and the client IP return $clientIps ? array_reverse($clientIps) : array($firstTrustedIp); } 

正如有人以前所说,这里的关键是你为什么要存储用户的ips。

我会举一个我从事的注册系统的例子,当然这个解决scheme只是为了在我的search中频繁出现的这个旧的讨论中做出贡献。

许多php注册库使用ip来扼杀/locking基于用户ip的失败尝试。 考虑这个表格:

 -- mysql DROP TABLE IF EXISTS `attempts`; CREATE TABLE `attempts` ( `id` int(11) NOT NULL AUTO_INCREMENT, `ip` varchar(39) NOT NULL, /*<<=====*/ `expiredate` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- sqlite ... 

然后,当用户尝试进行login或任何与密码重置相关的服务时,会在开始时调用一个函数:

 public function isBlocked() { /* * used one of the above methods to capture user's ip!!! */ $ip = $this->ip; // delete attempts from this ip with 'expiredate' in the past $this->deleteAttempts($ip, false); $query = $this->dbh->prepare("SELECT count(*) FROM {$this->token->get('table_attempts')} WHERE ip = ?"); $query->execute(array($ip)); $attempts = $query->fetchColumn(); if ($attempts < intval($this->token->get('attempts_before_verify'))) { return "allow"; } if ($attempts < intval($this->token->get('attempts_before_ban'))) { return "captcha"; } return "block"; } 

比如说, $this->token->get('attempts_before_ban') === 10和2个用户与前面的代码中的头部可以被欺骗的情况相同,然后每次尝试5次被禁止 ! 更糟糕的是,如果所有代码都来自同一个代理,那么只有前10个用户会被logging下来,其余的都将被禁止!

这里至关重要的是我们需要一个独特的表attempts索引,我们可以从这样的组合得到它:

  `ip` varchar(39) NOT NULL, `jwt_load varchar(100) NOT NULL 

其中jwt_load来自遵循json Web令牌技术的http cookie,我们仅存储应该为每个用户包含任意/唯一值的encryption有效载荷。 当然,请求应该修改为: "SELECT count(*) FROM {$this->token->get('table_attempts')} WHERE ip = ? AND jwt_load = ?" 而且class级也应该发起一个private $jwt

你几乎回答了你自己的问题! 🙂

 function getRealIpAddr() { if(!empty($_SERVER['HTTP_CLIENT_IP'])) //Check IP address from shared Internet { $IPaddress = $_SERVER['HTTP_CLIENT_IP']; } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) //To check IP address is passed from the proxy { $IPaddress = $_SERVER['HTTP_X_FORWARDED_FOR']; } else { $IPaddress = $_SERVER['REMOTE_ADDR']; } return $IPaddress; } 

资源

 /** * Sanitizes IPv4 address according to Ilia Alshanetsky's book * "php|architect?s Guide to PHP Security", chapter 2, page 67. * * @param string $ip An IPv4 address */ public static function sanitizeIpAddress($ip = '') { if ($ip == '') { $rtnStr = '0.0.0.0'; } else { $rtnStr = long2ip(ip2long($ip)); } return $rtnStr; } //--------------------------------------------------- /** * Returns the sanitized HTTP_X_FORWARDED_FOR server variable. * */ public static function getXForwardedFor() { if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { $rtnStr = $_SERVER['HTTP_X_FORWARDED_FOR']; } elseif (isset($HTTP_SERVER_VARS['HTTP_X_FORWARDED_FOR'])) { $rtnStr = $HTTP_SERVER_VARS['HTTP_X_FORWARDED_FOR']; } elseif (getenv('HTTP_X_FORWARDED_FOR')) { $rtnStr = getenv('HTTP_X_FORWARDED_FOR'); } else { $rtnStr = ''; } // Sanitize IPv4 address (Ilia Alshanetsky): if ($rtnStr != '') { $rtnStr = explode(', ', $rtnStr); $rtnStr = self::sanitizeIpAddress($rtnStr[0]); } return $rtnStr; } //--------------------------------------------------- /** * Returns the sanitized REMOTE_ADDR server variable. * */ public static function getRemoteAddr() { if (isset($_SERVER['REMOTE_ADDR'])) { $rtnStr = $_SERVER['REMOTE_ADDR']; } elseif (isset($HTTP_SERVER_VARS['REMOTE_ADDR'])) { $rtnStr = $HTTP_SERVER_VARS['REMOTE_ADDR']; } elseif (getenv('REMOTE_ADDR')) { $rtnStr = getenv('REMOTE_ADDR'); } else { $rtnStr = ''; } // Sanitize IPv4 address (Ilia Alshanetsky): if ($rtnStr != '') { $rtnStr = explode(', ', $rtnStr); $rtnStr = self::sanitizeIpAddress($rtnStr[0]); } return $rtnStr; } //--------------------------------------------------- /** * Returns the sanitized remote user and proxy IP addresses. * */ public static function getIpAndProxy() { $xForwarded = self::getXForwardedFor(); $remoteAddr = self::getRemoteAddr(); if ($xForwarded != '') { $ip = $xForwarded; $proxy = $remoteAddr; } else { $ip = $remoteAddr; $proxy = ''; } return array($ip, $proxy); }