1of0 / ip-utils
几个简单的包装类/实用工具,使处理IP地址和子网变得更加容易
dev-master
2020-05-29 18:04 UTC
Requires
- php: >=7.4
Requires (Dev)
- phpunit/phpunit: ^9.0
This package is auto-updated.
Last update: 2024-08-29 05:24:45 UTC
README
是什么
几个简单的包装类/实用工具,使处理IP地址和子网变得更加容易。
许可证
此项目采用MIT许可证。请参阅LICENSE.md。
需求
php >= 7.4
安装
composer require 1of0/ip-utils
为什么
免责声明:还有一些其他库可能更全面
然而,没有一个正好符合我构想的接口,一个依赖于bcmath
,另一个有一些我不太认同的方法。但话虽如此,它们似乎都有良好的测试覆盖率和实际应用,所以请随意选择!
因此,我主要构建这个是为了得到我想要的接口,并且除了php >= 7.4
之外没有其他依赖。
使用方法
请参阅生成的phpdoc以获取完整的API规范。
基本用法
/** @noinspection ForgottenDebugOutputInspection */
use OneOfZero\IpUtils\Factory;
use OneOfZero\IpUtils\IpAddress;
use OneOfZero\IpUtils\Subnet;
/** @var IpAddress $ip */
$ip = Factory::get()->parse('192.168.0.123');
/** @var Subnet $subnet */
$subnet = Factory::get()->parse('192.168.0.0/24');
var_dump($subnet->contains($ip));
// bool(true)
print_r([
(string)$subnet->getAddress(),
(string)$subnet->getNetworkAddress(),
(string)$subnet->getRouterAddress(),
(string)$subnet->getBroadcastAddress(),
(string)$subnet->getSubnetMask(),
$subnet->getCidr(),
$subnet->getPrefixLength(),
$subnet->getIdentifier(),
]);
// Array
// (
// [0] => 192.168.0.0
// [1] => 192.168.0.0
// [2] => 192.168.0.1
// [3] => 192.168.0.255
// [4] => 255.255.255.0
// [5] => 192.168.0.0/24
// [6] => 24
// [7] => c0a80000ffffff00
// )
集合
还可以查看ImmutableCollection
!
/** @noinspection ForgottenDebugOutputInspection */
use OneOfZero\IpUtils\IpAddress;
use OneOfZero\IpUtils\Subnet;
use OneOfZero\IpUtils\Collection;
$collection = new Collection([
'192.168.0.123',
'10.0.0.0/8',
IpAddress::parse('127.0.0.1'),
Subnet::parseCidr('192.168.0.0/24'),
]);
$collection->addItem('::1');
print_r($collection->getStringRepresentations());
// Array
// (
// [0] => 192.168.0.123
// [1] => 10.0.0.0/8
// [2] => 127.0.0.1
// [3] => 192.168.0.0/24
// [4] => ::1
// )
$collection->filterOutRedundantItems();
print_r($collection->getStringRepresentations());
// Array
// (
// [0] => 10.0.0.0/8
// [1] => 127.0.0.1
// [2] => 192.168.0.0/24
// [3] => ::1
// )
具体设计选择
这不是错误,这是功能!
子网行为
当使用不是网络地址的IP地址创建Subnet
实例(例如,192.168.0.10/24
而不是192.168.0.0/24
)时,IP地址将被保留并通过getAddress()
和getCidr()
返回。
但是,它将不会用于如contains()
、equals()
和getIdentifier()
的方法。
这影响了Collection
中Subnet
的行为。
例如
use OneOfZero\IpUtils\Collection;
$collection = new Collection(['192.168.0.10/24']);
$collection->getStringRepresentations();
// ['192.168.0.10/24']
$collection->addItem('192.168.0.20/24');
$collection->getStringRepresentations();
// ['192.168.0.20/24'] first item was replaced because both Subnets have the same identifier