matiasf matiasf - 1 year ago 91
MySQL Question

Check if IP is in subnet

I have a table A with IP addresses (ipNumeric) stored as unsigned ints and a table B with subnets (subnetNumeric):

INET_NTOA(ipNumeric) =
INET_NTOA(subnetNumeric) =

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?

Jon Jon
Answer Source

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

SELECT -1 << 8;

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:

SELECT (-1 << 8) & INET_ATON("") = INET_ATON("");

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 this X.Y.0.0/16 or X.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

SELECT (-1 << (33 - INSTR(BIN(INET_ATON("")), "0"))) &
       INET_ATON("") = INET_ATON("");