I have a MySQL table where I store IP ranges. It is setup in the way that I have the start address stored as a long, and the end address (and an id and some other data).
Now I have users adding ranges by inputting a start and end ip address, and I would like to check if the new range is not already (partially) in the database.
I know I can do a between query, but that doesn’t seem to work with 2 different columns, and I also cannot figure out how to pass a range to compare it.
Doing it in a loop in PHP is a possibility, but would with a range of e.g. 132.0.0.0-199.0.0.0 be quite a big amount of queries..
When you say you have the addresses stored as a
long, I’m assuming you mean you’ve got them stored such that (say) 10.1.2.3 will be stored as 0x0a010203. In that case, to find if an address is already present, you can do:and then if you get any rows back, the address is already in the table. (replace
<NEWADDR>with the new address, of course!)As for checking overlapping rows, that’s only slightly more complicated:
i.e. the new range doesn’t overlap the old range provided that either it starts after it, or ends before it.