网络开发很多情况下都会遇到这种场景,判断某个IP是否属于某个cidr网段;但php官方并没有提供类似功能函数,以前我的做法都是将IP和整个网段转换为整数,再通过判断整数是否在范围以内,以此确定是否属于此网段,但我觉得方法太笨,于是一番查找,发现一位前辈留下了笔记。
地址:https://www.php.net/manual/en/ref.network.php#74656
笔记说明
A simple and very fast function to check against CIDR. Your previous examples are too complicated and involves a lot of functions call. Here it is (only with arithmetic operators and call only to ip2long () and split() ):
版本略旧,我替换了个别函数格式化了一下,代码如下:
| |
![Featured image of post [PHP] IPV4 CIDR 范围判断函数](/p/689/banner_hu_b4ce6cab8e6b90d.jpg)