I spend a lot of time lurking in the #PHP channel (efnet and freenode, please – no flamewars) and this topic is a commonly asked one that usually gets a simplified answer in the form of using strpos(), or at best an ip2long() in a greater than and less than answer.
Unfortunately although people usually understand that an IP address is simply an unsigned 32 bit integer, and is easily determined, usually with $_SERVER[‘REMOTE_ADDR’], where the real challenge is – is in specifying the range within which they wish to check that IP address. IP ranges are usually specified in three common ways (in increasing complexity):
- Wildcard: 192.168.10.*
- Start-End range: 10.1.0.0-10.1.255.255
- CIDR*: 172.16.1.0/24
* Classless Inter-Domain Routing
The Wildcard method, or “classy”, allows you to work at Class A (10.*.*.*), Class B (172.16.*.*) or Class C (192.168.10.*) levels of granularity which is how we used to do things in the old days (before the Web decided to make the Internet popular). But, increasingly, this just isn’t granular enough for practical purposes.
Thus was born CIDR (yes, I’m skipping talking about Start-End ranges for now). CIDR brought about the concept that we really didn’t need to break networks on 8, 16, 24 bit boundaries and we could be more granular by allowing the use of any number (from 2-30) to specify a range of networks. Details on why you can’t use “31” is beyond the scope of this article.
CIDR renamed the former Class A, B and C networks as /8, /16 and /24 respectively and reflects the left-most significant bits of the 32-bit IP address. Thus was born the ability to specify very specific IP ranges in the form a.b.c.d/xx. However, part of the problem with this is that although it concisely describes the network start and end, most normal mortal humans couldn’t decipher it. CIDR addressing can also be specified in the form of a longer netmask, e.g. a.b.c.d/255.255.255.224
Thus, the simplified form of Start IP – End IP was put in place for mere mortals and is typically used by those without a networking background. It also features heavily in consumer broadband routers and notably in Microsoft Windows DHCP server.
So having explained how a range, and by inference, that a netmask is, how can we use this knowledge to help us in determining if an IP is within a range?
What this article will attempt to do is guide you though the construction of algorithms to make the checking of IPs simpler.
Logically, Method 1 (the Wildcard), can be easily converted to Method 2 (Start-End range) by using setting Start and End to the Wildcard string and replacing the “*” character with 0 for the Start and 255 for the End, thus for example, “192.168.10.*” becomes “192.168.10.0-192.168.10.255” which should (I hope) be obvious to everyone.
We can then proceed to evaluate both Method1 and Method2 in the same way. In this we’re simply going to use the PHP built in function ip2long() on all 3 values and perform a mathematical check for Start <= IP <= End.
list($lower, $upper) = explode('-', $range, 2);
$lower_dec = ip2long($lower);
$upper_dec = ip2long($upper);
$ip_dec = ip2long($ip);
return ( ($ip_dec>=$lower_dec) && ($ip_dec<=$upper_dec) );
We have, however, a complicating factor here – PHP does not do unsigned integers (32 bit) – which would be necessary for this math to work properly. We can negate this by switing to floating point data types. PHP stores floating types as 64 bit and so will have no problem with IPv4 address space (note – this obviously isn’t granular enough for 128bit IPv6 addressing). Therefore the simplest way to solve the Start <= IP <= End problem with IPs and floating point numers is the following piece of code:
$lower_dec = (float)sprintf("%u",ip2long($lower));
$upper_dec = (float)sprintf("%u",ip2long($upper));
$ip_dec = (float)sprintf("%u",ip2long($ip));
return ( ($ip_dec>=$lower_dec) && ($ip_dec<=$upper_dec) );
Next we have the challenge of handing the CIDR netmasks. What we could do is to take a CIDR format IPaddress/netmask and calculate the Start and End IPs of that block and proceed as before – but that would be no fun – and would mean I haven’t really taught anything through this article.
The method we’re going to use here is how all the world’s Internet routers determine if a destination IP is in a specific CIDR address space. And we’re going to get down and dirty with bitmasks and logical bitwise operators.
So using a real world example, my webserver IP 22.214.171.124 and the netblock within which it resides is 126.96.36.199/27, how does this all work?
Well the /27 indicates that the first 27 bits of the IP address are the same network and IP address in that network (range) will have those same identical first 27 bits. Bits 28-32 are variable and allow 5 bits of variation. If you know your binary, then this means 32 possible IPs. (However with routing, you can’t use the bottom and top IP from any range as these are special and mean the network and broadcast addresses respectively. [This is also why a /31 isn’t much use (except for PPP links) as you can’t use the 2 addresses that space gives you]).
So thinking logically, bitwise, if I take my IP address and the CIDR spec, then all I have to do is check that the first 27 bits all match and I’m good. Correct. So how would we do this in PHP? Sound’s simple, lets just use PHP’s bitwise logical AND operator: &
In order to do this we need to convert 27 into what 27 really means – a 32 bit number of 27 ones and 5 zeros in binary (which is what 255.255.255.224 really looks like).
In pseudo-code you could then do if (IP & BITMASK) == (RANGE & BITMASK) then all is good and you know that the IP is within the range.
Visualising this using our real IP address (using the very handy unix tool ipcalc):
Address: 188.8.131.52 01010000.01001100.11001001.00100101
Netmask: 255.255.255.224 11111111.11111111.11111111.11100000
Wildcard: 0.0.0.31 00000000.00000000.00000000.00011111
Network: 184.108.40.206/27 01010000.01001100.11001001.00100000
HostMin: 220.127.116.11 01010000.01001100.11001001.00100001
HostMax: 18.104.22.168 01010000.01001100.11001001.00111110
Broadcast: 22.214.171.124 01010000.01001100.11001001.00111111
You can see this in the Wildcard line of 0.0.0.31, and the Network ORed with Wildcard results in the Broadcast address: 126.96.36.199.
Knowing this, then the IP address ANDed with the Network address will result in the same value as the Range ANDed with the Network address and so can be used as a comparison for an IP residing within that broadcast range.
How can we work out this Network address in PHP, again we have two strategies, one is to so a simple substr() and take the left most significant bits of the range and then simply pad out to the right with 0s. Or we can do some math with “NOT of 2 to the power of (32-range) – 1”. Thus for our value /27 this gives us the decimal value 31, NOTed results in (65536-31) (representational in the bit form – PHP will see it as a negative integer, but we don’t need to worry about that).
I’m sure by now, your screaming for some code (and if you stuck around this long, you really deserve it).
Code to manipulate a range/netmask into a broadcast address, using math, assuming:
$ip = "188.8.131.52";
$range = "184.108.40.206";
$netmask = 27;
We can convert the IPs to long integers using ip2long (denoted by variable_dec – dec being short for decimal):
$range_dec = ip2long($range);
$ip_dec = ip2long($ip);
This gives us the basis of our math, we now just need to work out the broadcast address.
Strategy 1 using str_pad to create a string by padding with 1s and 0s.
$netmask_dec = bindec( str_pad('', $netmask, '1')
. str_pad('', 32-$netmask, '0') );
We can achieve the same result though mathematics by NOTing the wildcard value. This is our Strategy 2:
$wildcard_dec = pow(2, (32-$netmask)) - 1;
$netmask_dec = ~ $wildcard_dec;
Once we know the netmask address (in decimal) as we have here, we can know that, if by ANDing this with the original IP to check results against the Range ANDed with the Netmask, then the IP is within the range defined by the range/mask.
This can be checked easily with:
return (($ip_dec & $netmask_dec) == ($range_dec & $netmask_dec));
I have pulled all of this logic together in a easily included file to provide a single function called ip_in_range($ip, $range) in which $ip is the IP address you want to validate and $range is a any of the above formats, Wildcard, Start-End addressing or CIDR. The function will return a simple TRUE or FALSE if the IP is in that range.
The source code to the all-in function is available here:
With an example run (and source code):
I hope this article has been educational, please feel free to leave comments or feedback.
Update: There have been questions about PHP’s signed integers and my use of bit operations in the code. It is important to recognise that when dealing with signed or unsigned 32 bit integers purely as bit patterns for masking with a netmask or broadcast address pattern – the fact that a number (220.127.116.11 or above) really is negative, doesn’t have any impact on the validity of the result. The only impact to not having signed 32 bit integers is in the Start-End range check (example 2 above: 10.1.0.0-10.1.255.255) where a range spanning the switch from positive to negative would be catastrophic to the check. We can safely work around that problem by using floating point numbers as we are only doing <= and >= comparisons and not attempting any bitwise operators (which don’t work on floats).