123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122 |
- <?php
- namespace yii\helpers;
- class BaseIpHelper
- {
- const IPV4 = 4;
- const IPV6 = 6;
-
- const IPV6_ADDRESS_LENGTH = 128;
-
- const IPV4_ADDRESS_LENGTH = 32;
-
- public static function getIpVersion($ip)
- {
- return strpos($ip, ':') === false ? self::IPV4 : self::IPV6;
- }
-
- public static function inRange($subnet, $range)
- {
- list($ip, $mask) = array_pad(explode('/', $subnet), 2, null);
- list($net, $netMask) = array_pad(explode('/', $range), 2, null);
- $ipVersion = static::getIpVersion($ip);
- $netVersion = static::getIpVersion($net);
- if ($ipVersion !== $netVersion) {
- return false;
- }
- $maxMask = $ipVersion === self::IPV4 ? self::IPV4_ADDRESS_LENGTH : self::IPV6_ADDRESS_LENGTH;
- $mask = isset($mask) ? $mask : $maxMask;
- $netMask = isset($netMask) ? $netMask : $maxMask;
- $binIp = static::ip2bin($ip);
- $binNet = static::ip2bin($net);
- return substr($binIp, 0, $netMask) === substr($binNet, 0, $netMask) && $mask >= $netMask;
- }
-
- public static function expandIPv6($ip)
- {
- $hex = unpack('H*hex', inet_pton($ip));
- return substr(preg_replace('/([a-f0-9]{4})/i', '$1:', $hex['hex']), 0, -1);
- }
-
- public static function ip2bin($ip)
- {
- if (static::getIpVersion($ip) === self::IPV4) {
- return str_pad(base_convert(ip2long($ip), 10, 2), self::IPV4_ADDRESS_LENGTH, '0', STR_PAD_LEFT);
- }
- $unpack = unpack('A16', inet_pton($ip));
- $binStr = array_shift($unpack);
- $bytes = self::IPV6_ADDRESS_LENGTH / 8;
- $result = '';
- while ($bytes-- > 0) {
- $result = sprintf('%08b', isset($binStr[$bytes]) ? ord($binStr[$bytes]) : '0') . $result;
- }
- return $result;
- }
- }
|