使用PHP验证非私有IP地址

前端之家收集整理的这篇文章主要介绍了使用PHP验证非私有IP地址前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试检查一个IP地址是否是内部(即私人)IP,但是我有一个好奇的结果:
filter_var('173.194.66.94',FILTER_VALIDATE_IP,FILTER_FLAG_NO_PRIV_RANGE); // returns 173.194.66.94
filter_var('192.168.0.1',FILTER_FLAG_NO_PRIV_RANGE); // returns false
filter_var('127.0.0.1',FILTER_FLAG_NO_PRIV_RANGE); // returns 127.0.0.1?

当然127.0.0.1是私人IP吗?我发现this bug report from 2010报告这是一个问题,但它被标记为固定的.这是一个回归,还是我误会这个过滤器呢?我使用PHP 5.4.6.

我猜这是因为127.0.0.1不是真正的私有IP范围,而是一个环回IP范围,如 here所述

Normally,when a TCP/IP application wants to send information,that information travels down the protocol layers to IP where it is encapsulated in an IP datagram. That datagram then passes down to the data link layer of the device’s physical network for transmission to the next hop,on the way to the IP destination.

However,one special range of addresses is set aside for loopback functionality. This is the range 127.0.0.0 to 127.255.255.255. IP datagrams sent by a host to a 127.x.x.x loopback address are not passed down to the data link layer for transmission. Instead,they “loop back” to the source device at the IP level. In essence,this represents a “short-circuiting” of the normal protocol stack; data is sent by a device’s layer three IP implementation and then immediately received by it.

The purpose of the loopback range is testing of the TCP/IP protocol implementation on a host. Since the lower layers are short-circuited,sending to a loopback address allows the higher layers (IP and above) to be effectively tested without the chance of problems at the lower layers manifesting themselves. 127.0.0.1 is the address most commonly used for testing purposes.

@L_301_2@手册对此具体问题发表了评论.

<?PHP
function FILTER_FLAG_NO_LOOPBACK_RANGE($value) {
    // Fails validation for the following loopback IPv4 range: 127.0.0.0/8
    // This flag does not apply to IPv6 addresses
    return filter_var($value,FILTER_FLAG_IPV6) ? $value :
        (((ip2long($value) & 0xff000000) == 0x7f000000) ? FALSE : $value);
}

$var = filter_var('127.0.0.1',FILTER_CALLBACK,array('options' => 'FILTER_FLAG_NO_LOOPBACK_RANGE'));
// Returns FALSE

$var = filter_var('74.125.19.103',array('options' => 'FILTER_FLAG_NO_LOOPBACK_RANGE'));
// Returns '74.125.19.103'

// To filter Private IP ranges and Loopback ranges
$var = filter_var('127.0.0.1',FILTER_FLAG_NO_PRIV_RANGE)  && filter_var('127.0.0.1',array('options' => 'FILTER_FLAG_NO_LOOPBACK_RANGE'));
// Returns FALSE
?>

猜你在找的PHP相关文章