aldin-sxr / ip-format-tools
一组用于处理IPv4/IPv6地址的实用工具。
v1.0.0
2019-10-13 11:46 UTC
Requires (Dev)
- jms/serializer: 1.7.*
- phpdocumentor/phpdocumentor: ^2.9
- phpunit/phpunit: ^8.0
Suggests
- ext-bcmath: Either BCMath or GMP are required.
- ext-gmp: Either GMP or BCMath are required; GMP is preferred, due to speed.
This package is auto-updated.
Last update: 2024-09-09 20:53:28 UTC
README
这是一个关于处理IP地址的实用方法的小集合。目前,该库提供将IPv4和IPv6地址转换为长整数的功能,以及反向操作。此外,该库还提供了一种在IPv6格式中表示IPv4地址的方法(例如,34.26.0.75 => ::ffff:221a:4b)。
安装
该库可通过Composer获得。
composer require aldin-sxr/ip-format-tools
安装后,请将vendor/autoload.php
和IPFormat
命名空间包含到您的项目中。
<?php require_once 'vendor/autoload.php'; use IPFormat\IPFormat;
请注意,该库需要GMP或BCMath扩展来处理大整数(在IPv6中看到),推荐使用GMP,因为它提供了更好的性能。
使用方法
该库提供三个主要方法:
IPFormat::ip_to_long()
IPFormat::long_to_ip()
IPFormat::ipv4_to_ipv6()
ip_to_long()
接受一个IPv4或IPv6地址,并返回相应的一个长整数。
echo IPFormat::ip_to_long('89.0.245.117'); // 1493235061 echo IPFormat::ip_to_long('fd44:5ff2:3::76cd'); // 336649705122095386261522076515346446029
long_to_ip()
接受一个长整数,并返回相应的一个IPv4或IPv6地址。
echo IPFormat::long_to_ip(45678892); // 2.185.1.44 echo IPFormat::long_to_ip('567235998141'); // ::84:11e6:71bd
ipv4_to_ipv6()
接受一个IPv4地址,并返回三种IPv6格式之一。
compressed
标志(默认值)返回一个压缩的IPv6地址(省略前导零,并将零的组替换为::
)。shortened
标志将零的组缩短为单个零,但不从地址中省略组。expanded
标志返回完整、展开的IPv6地址。
echo IPFormat::ipv4_to_ipv6('34.26.0.75', 'compressed'); // ::ffff:221a:4b echo IPFormat::ipv4_to_ipv6('34.26.0.75', 'shortened'); // 0:0:0:0:0:ffff:221a:004b echo IPFormat::ipv4_to_ipv6('34.26.0.75', 'expanded'); // 0000:0000:0000:0000:0000:ffff:221a:004b
文档
库文档使用phpDocumentor生成,可在以下位置找到: https://aldin-sxr.github.io/ip-format-tools/
测试
所有库方法都在PHPUnit中附带几个单元测试,这些测试位于tests/unit
下。