Page 1 of 1

Check if an IP is within a certain range

Posted: Wed Mar 24, 2004 3:01 pm
by Tubby
Hello,
I need to check if the users IP is within two IP ranges, how can I do this?

I was thinking that some kind of function that either returned 1 or 0 depending if the IP is within one of the ranges would be in order, but don't know how to go about doing that :(

Example:
The two defined IP ranges are 10.0.0.1 -> 10.0.0.255 and 192.168.0.1 -> 192.168.0.255
If the visitors IP was 192.168.0.54 the function would return 1
If the visitors IP was 10.0.0.122 the function would return 1
If the visitors IP was 69.56.28.144 the function would return 0
(or the opposite way round, I'm easy :lol: )

Hopefully you understand what I'm trying to do.

Any guidence or complete function would be appreciated.

Posted: Wed Mar 24, 2004 3:22 pm
by mjseaden
The dots '.'s in the IP address are terminators. Search through the string to find the dots, then simply separate the ip into its corresponding numbers. For 10.0.0.1 -> 10.0.0.255, you would first check that the first three indexes were 10,0 and 0. Then you would check if the final one had a range 1->255. You can separate the numbers using a function I would guess similar to mid(), then convert to a number using a conversion function (Google should tell you this).

A similar routine would apply for the second IP address.

Do you like Porn Flakes in the morning?

Posted: Wed Mar 24, 2004 3:52 pm
by PrObLeM

Code: Select all

function searchip($ip) //10.0.0.34 or what ever
{
$numbers = explode(".", $ip);
if($numbers[0] == 10 && $numbers[1] == 0 && $numbers[2] == 0)
{ return 1;}
if($numbers[0] == 192 && $numbers[1] == 168 && $numbers[2] == 0)
{ return 1;}
else
{return 0;}
}
you dont really need to check the range of the last one cause it only goes from 0 - 255
UNLESS you dont want 10.0.0.0 to return 1
if you do not want to include the 0 then just add && $numbers[3] >=1 to both if statments

Posted: Wed Mar 24, 2004 4:06 pm
by Tubby
Thanks mjseaden (yes I do like pornflakes in the morning :p) and Problem, That code looks like exactly what I need.
I'll give it a shot tomorrow and see how it goes :D

Posted: Wed Mar 24, 2004 4:42 pm
by redmonkey
Just thought I'd throw in an alternative.

Code: Select all

function valid_ip($ip)
{
	if (preg_match('/^(10\.0|192\.168)\.0\.(?!0)/', $ip))
	{
		return 1;
	}
	return 0;
}
This will not validate 10.0.0.0 or 192.168.0.0 if that is required then remove the (?!0)

Posted: Wed Mar 24, 2004 4:44 pm
by tim
red is the bloody KING of regular expressions.

its plain n simple as that :D :D :D

Posted: Wed Mar 24, 2004 5:29 pm
by Tubby
Even better redmonkey, thanks :mrgreen:

Posted: Wed Mar 24, 2004 5:42 pm
by PrObLeM
ture...very ture

Posted: Wed Mar 24, 2004 6:20 pm
by Weirdan
here is general function to check the ip against the range in CIDR notation (like '192.168.1.0/24'):
viewtopic.php?p=98477