The good news is that no special attention needs to be given to parsing the remote ip address at all. "whois" queries againts ARIN's database will resolve to the delegated ISP regardless of which ip you query on (ie. you don't have to quess at what the network address is or what the subnet mask is). Here's the script that pulls up the whois information:
<?php
$remoteip = $GLOBALS['REMOTE_ADDR'];
$forwarder = $GLOBALS['HTTP_X_FORWARDED_FOR'];
if (($forwarder != "")&&($forwarder != "unknown")) $remoteip = $forwarder;
echo "Whois query on $remoteip...\n";
$fp = fsockopen("arin.net", 43, $errno, $errstr);
if (!$fp) {
echo "ERROR: $errno - $errstr<br>\n";
} else {
fwrite($fp,"$remoteip\n");
echo "<pre>\n";
echo fread($fp, 1000);
echo "</pre>\n";
fclose($fp);
}
?>
The output could be captured to a string and then parsed. The last ISP in the list should be the one with the narrowest scope of assignment. For example, my address shows that the first allocation of my IP is to C&W, who has then sub-delegated it to a much smaller ISP (MainNet):
Cable & Wireless USA (NETBLK-CW-10BLK) CW-10BLK 208.128.0.0 - 208.175.255.255
MAIN NET (NETBLK-CW-208-163-84) CW-208-163-84 208.163.84.0 - 208.163.87.255
From here, we could query on: "!NETBLK-CW-208-163-84"
And we would get the address name and phone number of the ISP's technical contact.
Pretty cool, huh?
BTW, the validity of this info depends on ISP's appropriately SWIP'ing their delegated address space through their upstream or ARIN.