how to compare a string to range

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
desmi
Forum Commoner
Posts: 64
Joined: Sun Jun 15, 2008 4:55 am

how to compare a string to range

Post 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?
filippo.toso
Forum Commoner
Posts: 30
Joined: Thu Aug 07, 2008 7:18 am
Location: Italy
Contact:

Re: how to compare a string to range

Post by filippo.toso »

Convert the IP to numbers using http://www.php.net/ip2long and use >= and <= operators for the comparison.
desmi
Forum Commoner
Posts: 64
Joined: Sun Jun 15, 2008 4:55 am

Re: how to compare a string to range

Post 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?
filippo.toso
Forum Commoner
Posts: 30
Joined: Thu Aug 07, 2008 7:18 am
Location: Italy
Contact:

Re: how to compare a string to range

Post 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).
Last edited by filippo.toso on Fri Aug 08, 2008 2:02 pm, edited 1 time in total.
desmi
Forum Commoner
Posts: 64
Joined: Sun Jun 15, 2008 4:55 am

Re: how to compare a string to range

Post by desmi »

ok thanks, ill try to solve it out :)
Post Reply