Search code examples
phprangeip-address

PHP Check if IP Address is in a range of IP Addresses


The mission for me is to check whether a given IP Address is between a IP Address range. For example whether the IP Address 10.0.0.10 is in the range of 10.0.0.1 and 10.0.0.255. I was looking for something but I wasn't able to find something to suit this exact need.

So I wrote something simple which works for my purpose. So far it's working nicely.


Solution

  • This is something small I came up with. I am sure there are other ways to check, but this will do for my purposes.

    For example if I want to know if the IP Address 10.0.0.1 is between the range 10.0.0.1 and 10.1.0.0 then I would run the following command.

    var_dump(ip_in_range("10.0.0.1", "10.1.0.0", "10.0.0.1")); 
    

    And in this case it returns true confirming that the IP Address is in the range.

        # We need to be able to check if an ip_address in a particular range
        function ip_in_range($lower_range_ip_address, $upper_range_ip_address, $needle_ip_address)
        {
            # Get the numeric reprisentation of the IP Address with IP2long
            $min    = ip2long($lower_range_ip_address);
            $max    = ip2long($upper_range_ip_address);
            $needle = ip2long($needle_ip_address);            
    
            # Then it's as simple as checking whether the needle falls between the lower and upper ranges
            return (($needle >= $min) AND ($needle <= $max));
        }