I’m trying to implement an IP banning system into my web app using MySQL, i know i can do it using .htaccess but that’s not neat to me.
Basically my current table is:
ip_blacklist(id, ip, date)
and in php i look up the database for the client IP to see if it’s blocked or not:
$sql = "SELECT ip FROM ip_blacklist WHERE ip = ? LIMIT 1"
$query = $this->db->query($sql, array($ip));
if($query->num_rows() > 0){
// Gotcha
}
Now.. this is working fine, but i want to be able to enter wildcard IP ranges in the database like:
42.21.58.*
42.21.*.*
53.*.*.*
How to do that?
Thanks in advance.
If you will always be checking one IP address at a time and your banned ranges never intersect, you should store the start and end addresses of the ranges to ban in numeric format.
Say, you want to ban
192.168.1.0to192.168.1.15which is192.168.1.0/28.You create a table like this:
, insert the range there:
then check:
The
ORDER BYandLIMITparts are required for the query to be efficient.This, as was stated before, assumes non-intersecting blocks and one IP at a time.
If the blocks intersect (for instance, you ban
192.168.1.0/28and192.168.1.0/24at the same time), the query may return false negatives.If you are want to query more than one IP at a time (say, update a table with a long list of IP addresses), then this query will be inefficient (
MySQLdoes not optimizerangein correlated subqueries well)In both these cases, you should need to store your ranges as
LineStringand use spatial indexes for fast searches: