[英]PHP : Matching an IP in a range between? (IPv4 and IPv6)
Is it a good idea to use inet_pton()
function to match an IP in a specific range? 使用
inet_pton()
函数在特定范围内匹配IP是个好主意吗? And is it good to use it for both IPv4 and IPv6 ? 将它同时用于IPv4和IPv6是否很好?
For example: 例如:
$start = inet_pton('192.168.0.1');
$end = inet_pton('195.200.0.200');
$ip = inet_pton($_SERVER['REMOTE_ADDR']);
if($ip >= $start && $ip <= $end) {
echo 'in range';
}
else {
echo 'not in range';
}
Use PHP's ip2long function. 使用PHP的ip2long函数。 It will convert IPv4 to numbers.
它将IPv4转换为数字。
Try this code:- 试试这个代码:
$start = ip2long('192.168.0.1');
$end = ip2long('195.200.0.200');
$ip = ip2long($_SERVER['REMOTE_ADDR']);
For both IPv4 and IPv6 addresses use this function for global use. 对于IPv4和IPv6地址,都可以将此功能用于全局用途。
function ipaddress_to_ipnumber($ipaddress) {
$pton = @inet_pton($ipaddress);
if (!$pton) { return false; }
$number = '';
foreach (unpack('C*', $pton) as $byte) {
$number .= str_pad(decbin($byte), 8, '0', STR_PAD_LEFT);
}
return base_convert(ltrim($number, '0'), 2, 10);
}
$start = ipaddress_to_ipnumber("192.168.178.255");
$end = ipaddress_to_ipnumber('195.200.0.200');
$ip = ipaddress_to_ipnumber($_SERVER['REMOTE_ADDR']);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.