Y
Y
Yuri Pikhtarev2011-05-04 16:09:44
PHP
Yuri Pikhtarev, 2011-05-04 16:09:44

Checking if an IP address range is within another IP address range in PHP?

Good day.

It was necessary to implement such a thing: there is a pool of addresses, client addresses with different masks are allocated from it. The task is to allocate IP addresses without allowing special fragmentation (IPs can be returned from clients). When selecting a range, how can I check if it intersects with previously selected ranges?

It is quite easy to check if an IP address is in a range of addresses, you can find many examples on the Internet on this issue, but here is the script logic for checking, for example, the following situation: does the range 192.168.0.0/16 include another, smaller range 192.168.1.0 /30 - I can't think.

Can anyone suggest a solution to this problem?

Answer the question

In order to leave comments, you need to log in

5 answer(s)
R
Riateche, 2011-05-04
@Exileum

1. Convert ip to numbers using ip2long. We have the lower bounds of the ranges.
2. Calculate the number of addresses in the range using the formula 2^(32-x), x is the last digit in the subnet designation.
3. We add the number of addresses to the lower bound, we get the upper bound (not inclusive).
4. Compare the boundaries of the ranges as numbers, check if the first range is included in the second one.

I
Ilya_Drey, 2011-05-04
@Ilya_Drey

Convert network and mask to binary format and see.
From your example: Accordingly, yes 192.168.1.0/30 is included in 192.168.0.0/16, but 192.169.0.0/30 is not included:
Network: 192.168.0.0/16 11000000.10101000.00000000.00000000
Netmask: 255.255.0.0 11111111.11111111.00000000.00000000
Network: 192.168.1.0/30 11000000.10101000.00000001.00000000
Netmask: 255.255.255.252 11111111.11111111.11111111.11111100

Network: 192.169.0.0/16 11000000.10101001.00000000.00000000
Netmask: 255.255.0.0 11111111.11111111.00000000.00000000

D
Denis, 2011-05-04
@uscr

Attention! Now there will be a very stupid comment from a person far from programming.
I propose the following algorithm: We
generate a list A of addresses for the network 192.168.0.0/16 We
generate a list B of addresses for the network 192.168.1.0/30
We look at which list has fewer elements (we are looking for a smaller range) We
check whether the first and last element from the smaller list is included in larger list.
If only one element (first or last) is included, we look at how to handle such overlapping ranges.

Z
zloyshaman, 2011-05-04
@zloyshaman

Are the ranges continuous? You check the first and last of one IP range for entry into another range. Then vice versa.

P
Puma Thailand, 2011-05-04
@opium

PHP has standard functions for working with ip ranges, look in the ip reference? already mentioned ip2long above

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question