本文介绍了匹配给定IP范围/掩码的IPv4地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

无论是使用PHP还是RegExp(或同时使用这两者),如何匹配一系列IP地址?

Either with PHP or a RegExp (or both), how do I match a range of IP addresses?

10.210.12.12
10.253.12.12
10.210.12.254
10.210.12.95
10.210.12.60

样本范围

10.210.12.0/24
10.210.12.0/16
10.210.*.*
10.*.*.*

我知道我可以做到:

?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)

...但是没有考虑范围.它只是让您匹配传入的号码,以查看它是不是每个八位位组为0-255的IP地址.

...but it doesn't take ranges into account. It merely lets you match an incoming number to see if it's an IP address where each octet is 0-255.

在ip.long函数的php.net的注释中也找到了该函数.

There's also this function that I found in a comment at php.net on the ip2long function.

function ip_in_network($ip, $net_addr, $net_mask){
    if($net_mask <= 0){ return false; }
        $ip_binary_string = sprintf("%032b",ip2long($ip));
        $net_binary_string = sprintf("%032b",ip2long($net_addr));
        return (substr_compare($ip_binary_string,$net_binary_string,0,$net_mask) === 0);
}

ip_in_network("192.168.2.1","192.168.2.0",24); //true
ip_in_network("192.168.6.93","192.168.0.0",16); //true
ip_in_network("1.6.6.6","128.168.2.0",1); //false

简短而甜美,但与星号情况不符.我也不知道它是否完全正确,因为当我认为这将是错误的时,它会返回正确的结果:

It's short and sweet, but doesn't match the asterisk situation. I also don't know if it's entirely accurate because it returns a true result on this when I thought it would be a false:

echo ip_in_network("192.168.2.1","192.167.0.0",1);

...但也许我误会了/1的含义.也许我需要使用/24.

...but perhaps I misunderstand what the /1 would be. Perhaps I needed to use /24.

推荐答案

使用此库: https://github .com/S1lentium/IPTools

//Check if IP is within Range:

echo Range::parse('192.168.1.1-192.168.1.254')->contains(new IP('192.168.1.5')); // true
echo Range::parse('::1-::ffff')->contains(new IP('::1234')); // true

这篇关于匹配给定IP范围/掩码的IPv4地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 13:09
查看更多