Click to See Complete Forum and Search --> : [RESOLVED] Check IP address within NetRange


tca
09-05-2007, 11:12 PM
Scratching my head on this one.

I want to check an IP address against the NetRange of the provider.

Suppose I have an IP of 23.23.45.32 and the NetRange of the provider is 23.0.0.0 - 23.255.255.255.

Is there a way to construct an array or something that will match the returned IP against the provider's NetRange? Preferably without having to type in each instance of the NetRange.:rolleyes:

TC

tca
09-06-2007, 08:30 PM
It ain't pretty, but here is my solution:


<?php
$range = "182.34.0.0:182.255.255.255"; //just some made up range
list ($min, $max) = explode(':', $range);
list ($min1, $min2, $min3, $min4) = explode('.', $min);
list ($max1, $max2, $max3, $max4) = explode('.', $max);
$excluded = "182.34.67.50"; //just some made up IP address
list ($ex1, $ex2, $ex3, $ex4) = explode('.', $excluded);
if ($ex1 >= $min1 && $ex1 <= $max1 && $ex2 >= $min2 && $ex2 <= $max2 && $ex3 >= $min3 && $ex3 <= $max3 && $ex4 >= $min4 && $ex4 <= $max4) $exclude = TRUE;
if ($exclude) echo $excluded . ' is excluded'; //trap to check the output
?>


I'll probably make this into a function and pass the Range from a database and the IP from gethostbyaddr($_SERVER['REMOTE_ADDR'])

Any suggestions or improvements welcome.

TC

pgregg
09-11-2007, 04:16 AM
A little overengineered there :)

$lower = iptolong('23.0.0.0');
$upper = iptolong('23.255.255.255');
$check = iptolong('23.23.45.32');
if ($check >= $lower && $check <= $upper) { // target IP is in range.

tca
09-11-2007, 02:56 PM
A little overengineered there :)



That's why I love this forum. :D

BTW, it's ip2long.


Thanks! Works perfectly.

TC