I have an IP address and I'm given two other IP addresses which together creates an IP range. I want to check if the first IP address is within this range. How can i find that out in PHP?
相关问题
- Views base64 encoded blob in HTML with PHP
- Laravel Option Select - Default Issue
- PHP Recursively File Folder Scan Sorted by Modific
- Can php detect if javascript is on or not?
- Using similar_text and strpos together
This website offers a great guide and code to do this (which was the first result of a Google search for this question):
Btw, in case you need to check multiple ranges at once you can add few rows to the code in order to pass array of ranges. The second argument can be an array or string:
With
ip2long()
it's easy to convert your addresses to numbers. After this, you just have to check if the number is in range:I would always suggest ip2long, but sometimes you need to check networks and etc. I've built in the past a IPv4 Networking class, which can be found here on HighOnPHP.
The nice thing about working with IP addressing is it's flexibility especially when using BITWISE operators. AND'ing, OR'ing and BitShifting will work like a charm.
Comparing in range (Including Ipv6 support)
The following two functions were introduced in PHP 5.1.0,
inet_pton
andinet_pton
. Their purpose is to convert human readable IP addresses into their packedin_addr
representation. Since the result is not pure binary, we need to use theunpack
function in order to apply bitwise operators.Both functions support IPv6 as well as IPv4. The only difference is how you unpack the address from the results. With IPv6, you will unpack with contents with A16, and with IPv4, you will unpack with A4.
To put the previous in a perspective here is a little sample output to help clarify:
We demonstrate above that the inet_* family supports both IPv6 and v4. Our next step will be to translate the packed result into an unpacked variable.
Note : The current function returns the first index of an array. It is equivelant to saying $array[0].
After the unpacking and packing, we can see we achieved the same result as input. This is a simple proof of concept to ensure we are not losing any data.
Finally use,
Reference: php.net
I found this little gist which has simpler/shorter solution than already mentioned here.
Second argument (range) can either be a static ip such as 127.0.0.1 or a range like 127.0.0.0/24.