Page 1 of 1

how to compare a string to range

Posted: Fri Aug 08, 2008 8:58 am
by desmi
Ok as the subject describes.. well, it should.. :

I have an ip, lets say: 213.204.37.x
I want to compare if it exists between range: 213.204.37.180 - 213.204.39.255
i have a list of ip ranges, exactly 723 different ranges, and i want to compare if that ip fits to any of them.

Any suggestions what method to use?

Re: how to compare a string to range

Posted: Fri Aug 08, 2008 9:01 am
by filippo.toso
Convert the IP to numbers using http://www.php.net/ip2long and use >= and <= operators for the comparison.

Re: how to compare a string to range

Posted: Fri Aug 08, 2008 9:31 am
by desmi
ip2long sounds good, but how to convert all ranges at once? or should i convert my whole range list to longs permanently?

and when i have these ranges in .dat file listed as:

range1start range1end
range2start range2end

..and so on, how should i read them from that list?

Re: how to compare a string to range

Posted: Fri Aug 08, 2008 10:01 am
by filippo.toso
If the range is fixed (i.e. you update it once a while), place the values in an array and use a for loop to verify if the IP is contained in one of the ranges.

In alternative use an array ordered by "from" value and execute a binary search to identify the range and verify if the IP is within it (very fast solution).

Re: how to compare a string to range

Posted: Fri Aug 08, 2008 11:54 am
by desmi
ok thanks, ill try to solve it out :)