Skip to content

Commit dbed72e

Browse files
committed
Fixed wrong value returned by cidrToIpv6 function
1 parent 7637188 commit dbed72e

File tree

3 files changed

+15
-27
lines changed

3 files changed

+15
-27
lines changed

docs/source/conf.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,8 @@
99
copyright = '2023, IP2Location'
1010
author = 'IP2Location'
1111

12-
release = '9.7.0'
13-
version = '9.7.0'
12+
release = '9.7.1'
13+
version = '9.7.1'
1414

1515
# -- General configuration
1616

src/Database.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ class Database
1212
*
1313
* @var string
1414
*/
15-
public const VERSION = '9.7.0';
15+
public const VERSION = '9.7.1';
1616

1717
/**
1818
* Unsupported field message.

src/IpTools.php

Lines changed: 12 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -194,37 +194,25 @@ public function cidrToIpv6($cidr)
194194

195195
list($ip, $range) = explode('/', $cidr);
196196

197-
// Convert the IPv6 into binary
198-
$binFirstAddress = inet_pton($ip);
197+
$parts = explode(':', $this->expandIpv6($ip));
199198

200-
// Convert the binary string to a string with hexadecimal characters
201-
$hexStartAddress = @reset(@unpack('H*0', $binFirstAddress));
199+
$bitStart = str_repeat('1', $range) . str_repeat('0', 128 - $range);
200+
$bitEnd = str_repeat('0', $range) . str_repeat('1', 128 - $range);
202201

203-
// Get available bits
204-
$bits = 128 - $range;
202+
$floors = str_split($bitStart, 16);
203+
$ceilings = str_split($bitEnd, 16);
205204

206-
$hexLastAddress = $hexStartAddress;
205+
$start = [];
206+
$end = [];
207207

208-
$pos = 31;
209-
while ($bits > 0) {
210-
// Convert current character to an integer
211-
$int = hexdec(substr($hexLastAddress, $pos, 1));
212-
213-
// Convert it back to a hexadecimal character
214-
$new = dechex($int | (pow(2, min(4, $bits)) - 1));
215-
216-
// And put that character back in the string
217-
$hexLastAddress = substr_replace($hexLastAddress, $new, $pos, 1);
218-
219-
$bits -= 4;
220-
--$pos;
208+
for ($i = 0; $i < 8; ++$i) {
209+
$start[] = dechex(hexdec($parts[$i]) & hexdec(base_convert($floors[$i], 2, 16))) . ':';
210+
$end[] = dechex(hexdec($parts[$i]) | hexdec(base_convert($ceilings[$i], 2, 16))) . ':';
221211
}
222212

223-
$binLastAddress = pack('H*', $hexLastAddress);
224-
225213
return [
226-
'ip_start' => $this->expand(inet_ntop($binFirstAddress)),
227-
'ip_end' => $this->expand(inet_ntop($binLastAddress)),
214+
'ip_start' => $this->expandIpv6(substr(implode('', $start), 0, -1)),
215+
'ip_end' => $this->expandIpv6(substr(implode('', $end), 0, -1)),
228216
];
229217
}
230218

0 commit comments

Comments
 (0)