Sorry, I did my query backwards, it should be..
SELECT COUNT(ip) as ip_matches FROM ipaddrs WHERE ip = LEFT('$theip',LENGTH(ip));
So if in your table you have 123.765 then any full address that starts with 123.765 will be counted, thus banned.
This is the shortest, and easiest, way I can think of and does not use like, nor requires an exact match of the full IP.
And like laserlight is saying, just trying to put as much as possible in the query so the database does the work.