PHP MySQL find IP address (between) stored IP address ranges

dev09 used Ask the Experts™

I am wondering how to code a PHP MySQL 'SQL' query to find the given IP address between 2 stored IP address ranges.

I am trying this:
$theIp  = '';
$result = mysqli_query($link,"SELECT * FROM `ipAddresses` WHERE `start` <= '$theIp' AND `end` >= '$theIp'") or die(mysql_error());

But it doesn't seem to be working correctly.  Should i store the IP data differently? Not in one field.

Thanks in advance!
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Check out the inet_aton MySQL function which will convert the IP address to an integer (

You should be able to do something like
$theIp  = '';
$result = mysqli_query($link,"SELECT * FROM `ipAddresses` WHERE inet_aton(`start`) <= inet_aton('$theIp') AND inet_aton(`end`) >= inet_aton('$theIp')") or die(mysql_error());

Open in new window

The syntax on that may be off as I didn't test it.
Ryan ChongSoftware Team Lead

one of the methods is to convert the IP Address to "IP Numbers" and then do the respective comparison.

in php you can use ip2long function:


in MySQL, use INET_ATON:
Ryan ChongSoftware Team Lead

ah, ok, think using INET_ATON is enough here, so no need to use php function ip2long.
Most Valuable Expert 2011
Top Expert 2016

This article shows how I've used IP numbers in PHP.  I used the MaxMind database to create a RESTful web service that could be used to identify the client country from its IP address.  Working code examples are included.

You might also want to look into the WordPress plugin called Akismet.  It's an anti-spam tool with IP awareness.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial