gpt4 book ai didi

php - 使用 PHP 验证非私有(private) IP 地址

转载 作者:可可西里 更新时间:2023-10-31 22:47:56 25 4
gpt4 key购买 nike

我正在尝试检查 IP 地址是否是仅内部(即私有(private))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_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE); // returns false
filter_var('127.0.0.1', FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE); // returns 127.0.0.1?

确定 127.0.0.1 算作私有(private) IP?我找到了 this bug report from 2010将此报告为问题,但已标记为已修复。这是回归,还是我误解了这个过滤器的作用?我正在使用 PHP 5.4.6。

最佳答案

我想那是因为 127.0.0.1 并不是真正的 private IP 范围,而是一个 loopback 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.

Filter flag 的手册对此特定问题有评论。

<?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_VALIDATE_IP, 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', FILTER_CALLBACK, 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_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE) && filter_var('127.0.0.1', FILTER_CALLBACK, array('options' => 'FILTER_FLAG_NO_LOOPBACK_RANGE'));
// Returns FALSE
?>

关于php - 使用 PHP 验证非私有(private) IP 地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17150100/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com