I wrote the following functions awhile back and never got around to testing them in a live environment. Basically, it queries arin to get the netblock, you can ban a whole netblock with these if you want (most of the time a bad idea.) I was uses them for tighter session security. Warning...whois rfc's might have changed since then!
<?PHP
function getRemoteNetworkRange($ip)
{
define("SEC_WHOIS_SERVER", "whois.arin.net");
define("SEC_WHOIS_PORT", 43);
$range = "";
if(@$sock=fsockopen(SEC_WHOIS_SERVER, SEC_WHOIS_PORT, $errno, $errstr, 30)) {
if(@fputs ($sock, "$ip\r\n")) {
while (!feof($sock)) {
$out .= fgets ($sock, 2048);
}
fclose($sock);
}
}
if (strpos($out, "NetRange:") !== false){
$ipPattern = "/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\s+\-\s+\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/";
preg_match($ipPattern, $out, $matches);
$range = $matches[0];
} elseif (strpos($out, "CIDR:") !== false) {
$ipPattern = "/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\/*\d*/";
preg_match($ipPattern, $out, $matches);
$range = $matches[0];
//Assume CIDR (Classless Inter-Domain Routing) notation.
list($network, $cidr) = explode("/", $range);
$broadcast = long2ip(ip2long($network) | (~ip2long(cidr2mask($cidr))));
$range = "$network-$broadcast";
} else {
$range = $ip;
}
$range = preg_replace("/[^\d\.\-\/]/", "",$range);
return $range;
}
function cidr2mask($mask_bits)
{
if($mask_bits > 31 || $mask_bits < 0) return("0.0.0.0");
$host_bits = 32-$mask_bits;
$num_hosts = pow(2,$host_bits)-1;
$netmask = ip2long("255.255.255.255")-$num_hosts;
return long2ip($netmask);
}
function inIPRange($ip, $range)
{
$returned = false;
if(strpos($range, "-") !== false){
list($network,$broadcast) = explode("-", $range);
$longip = ip2long($ip);
$longnetwork = ip2long($network);
$longbroadcast = ip2long($broadcast);
if ($longip > $longnetwork && $longip < $longbroadcast)
$returned = true;
} else {
if ($ip == $range)
$returned = true;
}
return $returned;
}
?>
By the way, this code is not copy and pasteable. The backslashes that should be in the regular expression patterns are stripped from the forum post automatically.