On Thu, 4 Apr 2002, Devin Atencio wrote:
> I was wondering If I made a database to store a list of IP CIDR
> in a database to block, how I could take an IP of a customer coming
> in and find a quick way if it matches a blocked IP in the database?
>
> For instance, in the database I would store something like this:
>
> 208.219.20.0/24
>
> Then if someone came in on 208.219.20.22, it would know that the entire
> class C was blocked. Is there an easy way to deal with this type of
> thing in PHP/MySQL?
Here's a little (tested just once but I'm guessing it's sound) example of
IP/subnet checking in PHP (converting between /24 and 255.255.255.0
notation is left as a homework exercise). Store them as INTs in MySQL and
you can use the & operator when selecting. However I don't think that
MySQL yet supports bitwise indexes so no promises on speed.
------------------
<?
if ($_REQUEST['go'])
{
$subnet = dotted_to_int($_REQUEST['subnet']);
$netmask = dotted_to_int($_REQUEST['netmask']);
$ip = dotted_to_int($_REQUEST['ip']);
if (($ip & $netmask) == $subnet) print 'Address is in range';
else print 'Address out of range';
}
function dotted_to_int($addr)
{
$octets = explode('.', ereg_replace('[^0-9\.]', '', $addr));
return
$octets[3] +
(256 * $octets[2]) +
(65536 * $octets[1]) +
(16777216 * $octets[0]);
}
?>
<form method="post" action="<?= $PHP_SELF ?>">
Subnet: <input name="subnet">
<br>Netmask: <input name="netmask">
<br>IP to check: <input name="ip">
<br><input name="go" value="Check it" type="submit"></form>
------------------
miguel
--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php