0

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.

Rudi Strydom
  • 4,417
  • 5
  • 21
  • 30
  • How are you specifying your range of addresses? – Anigel Aug 20 '13 at 13:57
  • Put more details in the question body for this to be a good Q&A – ಠ_ಠ Aug 20 '13 at 14:02
  • Do you want to get the subnet range of the IP, or check whether a detected address is within a specified array? – Daryl Gill Aug 20 '13 at 14:18
  • possible duplicate of [How to check an IP address is within a range of two IPs in PHP?](http://stackoverflow.com/questions/11121817/how-to-check-an-ip-address-is-within-a-range-of-two-ips-in-php) – DanMan Aug 09 '14 at 13:35

1 Answers1

14

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));
    }    
Rudi Strydom
  • 4,417
  • 5
  • 21
  • 30