leth / ip-address
IPv4 和 IPv6 地址及子网类,拥有强大的实用函数。
v2.0.1
2024-03-23 22:46 UTC
Requires
- php: >=8.1
- pear/math_biginteger: 1.0.3
Requires (Dev)
This package is auto-updated.
Last update: 2024-08-23 23:45:07 UTC
README
一套用于在 PHP 中处理 IP 地址的实用类。支持 IPv4 和 IPv6 方案。
要求
-
PHP 版本 5.3.0 或更高版本。
-
PEAR 的 Math_BigInteger 类
用于在 IPv6 地址上进行加法和减法操作,以及在 IPv6 地址块中查找 IP 地址。
示例
<?php use Leth\IPAddress\IP, Leth\IPAddress\IPv4, Leth\IPAddress\IPv6; // Creates an instance $ip = IP\Address::factory('127.0.0.1'); // Prints "127.0.0.1" echo $ip . "\n"; /** * IP\Address::factory(...) will attempt to guess the address version from the arguments */ // Returns an instance of IPv4\Address $ip = IP\Address::factory('127.0.0.1'); $ip = IPv4\Address::factory('127.0.0.1'); // Returns an instance of IPv6\Address $ip = IP\Address::factory('::1'); $ip = IPv6\Address::factory('::1'); /** * IP\NetworkAddress::factory(...) will also attempt to guess protocol versions */ // Can either be called with the subnet size encoded in the address string, $net_addr = IP\NetworkAddress::factory('192.168.0.1/24'); // Or as the second parameter $net_addr = IP\NetworkAddress::factory('192.168.0.1', 24); // Prints '192.168.0.0' echo $net_addr->get_network_address() . "\n"; // Prints '192.168.0.255' echo $net_addr->get_broadcast_address() . "\n"; // Prints '255.255.255.0' echo $net_addr->get_subnet_mask() . "\n"; /** * For each address of the specified network. */ $network = IPv4\NetworkAddress::factory('192.168.0.0/24'); foreach ($network as $ip) { // $ip is instance of IPv4\Address with value: // 192.168.0.0 // 192.168.0.1 // ... } $network = IPv4\NetworkAddress::factory('192.168.0.0/24'); // Prints '256' echo count($network); /** * Merge adjacent NetworkAddress blocks into larger blocks */ $small = array( IPv4\NetworkAddress::factory('192.168.0.0/24'), IPv4\NetworkAddress::factory('192.168.1.0/24') ); $merged = IP\NetworkAddress::merge($small); // Prints '1' echo count($merged); // Prints '1' echo $merged[0] == IP\NetworkAddress::factory('192.168.0.0/23'); /** * Get specified octet from IP */ $ipv4 = IP\Address::factory('192.168.1.102'); // Prints '102' echo $ipv4->get_octet(-1); // Prints '168' echo $ipv4[1]; $ipv6 = IP\Address::factory('2490::fa'); // Prints '250' echo $ipv6->get_octet(-1); // Prints '0' echo $ipv6[5];
测试用例
要运行测试用例,以下命令可以解决问题
-
无装饰测试
phpunit -c phpunit.xml.dist
-
将代码覆盖率报告生成到 './coverage/' 目录中
phpunit -c phpunit.xml.dist --coverage-html coverage
-
带有颜色和详细输出的
phpunit -c phpunit.xml.dist --colors --verbose
-
全部一起
phpunit -c phpunit.xml.dist --coverage-html coverage --colors --verbose