Pyh.conf’25: a new PHP conference for the Russian-speaking community

Voting

: two plus four?
(Example: nine)

The Note You're Voting On

Ian B
18 years ago
NOTE: ip2long() should NOT be used for CIDR calculation.
Instead, you should use something like the following:

<?php
/* get the base and the bits from the ban in the database */
list($base, $bits) = explode('/', $CIDR);

/* now split it up into it's classes */
list($a, $b, $c, $d) = explode('.', $base);

/* now do some bit shfiting/switching to convert to ints */
$i = ($a << 24) + ($b << 16) + ($c << 8) + $d;
$mask = $bits == 0 ? 0 : (~0 << (32 - $bits));

/* here's our lowest int */
$low = $i & $mask;

/* here's our highest int */
$high = $i | (~$mask & 0xFFFFFFFF);

/* now split the ip were checking against up into classes */
list($a, $b, $c, $d) = explode('.', $iptocheck);

/* now convert the ip we're checking against to an int */
$check = ($a << 24) + ($b << 16) + ($c << 8) + $d;

/* if the ip is within the range, including
highest/lowest values, then it's witin the CIDR range */
if ($check >= $low && $check <= $high)
return
1;
else
return
0;
?>

This means that you should check to see if the IP
address is of the correct format each time.

<< Back to user notes page

To Top