note 90344 modified in function.ip2long by danbrown
| From: | danbrown@php.net | Date: | Fri, 17 Apr 2009 16:38:10 +0000 |
| Subject: | note 90344 modified in function.ip2long by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-153446@lists.php.net to get a copy of this message | ||
Just want to add a comment to kaputt's valuable contribution to the task of matching hosts to
ip ranges, efficiently. The script works fine if the binary representation of the ip involves no
leading zeros. Unfortunately, the way decbin() seems to work, leading zeros in the binary
representation of the first ip quad get dropped. That is a serious matter if you're trying to
match all possible candidates in the checklist. In those cases the leading zeros need to be added
back to get accurate matches for values in the first quad between 0-127 (or the binary equivalent,
0-01111111).
The solution I came up with to address this issue was the following function:
<?php
function addLeadingZero($ip) {
if (($result = (32 - strlen($ip))) > 0)
return str_repeat("0", $result).$ip;
}
?>
--was--
Just want to add a comment to kaputt's valuable contribution to the task of matching hosts to
ip ranges, efficiently. The script works fine if the binary representation of the ip involves no
leading zeros. Unfortunately, the way decbin() seems to work, leading zeros in the binary
representation of the first ip quad get dropped. That is a serious matter if you're trying to
match all possible candidates in the checklist. In those cases the leading zeros need to be added
back to get accurate matches for values in the first quad between 0-127 (or the binary equivalent,
0-01111111).
The solution I came up with to address this issue was the following function:
function addLeadingZero($ip) {
if (($result = (32 - strlen($ip))) > 0)
return str_repeat("0", $result).$ip;
}
http://php.net/manual/en/function.ip2long.php