I have a table A with IP addresses (ipNumeric) stored as unsigned ints and a table B with subnets (subnetNumeric):
INET_NTOA(ipNumeric) = 192.168.0.1
INET_NTOA(subnetNumeric) = 192.168.0.0
I'd like to check if this IP is a member of a subnet.
The subnets are Class A, B and C.
Is this possible to do in reasonable time in MySQL on the fly or should the subnet ranges be precomputed?
I have a solution for when the addresses are stored as strings. So if you wish to make that part of your algorithm, you can use my solution here.
It is a little tricky, especially for IPv6. In IPv6 there can optionally be compressed segments, like 1::1 which is equivalent to 1:0:0:0:0:0:0:1, which is the main reason it is tricky.
The IPAddress Java library will produce mysql SQL to search for addresses in a given subnet. The link describes this problem in more detail. Disclaimer: I am the project manager.
The basic algorithm is to take the network section of the subnet address, then take each variant of that section (for example the two strings above are variants of the full address 1::1), then count the number of segment separators, then do a mysql substring on the address being matched, but also count the total separators in the address being matched.
Here is sample code:
Ouptut:
First create tables to support testing.
Now do a select finding matches between the tables based on address & mask = subnet. Here we assume class B subnets (255.255.0.0). No need to bit-shift as we can use the INET_ATON() function.
This is the MySQL function we use.
e.g. Find all the rows where t.ip is in the range 192.168.0.x where 0<=x<=255
Sure, it's doable. The idea is that we calculate the subnet mask by setting the most significant bits to 1, as many as dictated by the subnet class. For a class C, that would be
Then, AND the subnet mask with the IP address you have; if the IP is inside the subnet, the result should be equal to the subnet address -- standard networking stuff. So we end up with:
Update: Yes, it is necessary to know the network class or the subnet mask (which is equivalent information). Consider how could you handle the case where the subnet is
X.Y.0.0
if you did not have this information. Is thisX.Y.0.0/16
orX.Y.0.0/8
where the third octet just happens to be 0? No way to know.If you do know the subnet mask, then the query can be written as