01 <?php 02 function ip2cidr($ip_start, $ip_end) { 03 if(long2ip(ip2long($ip_start)) != $ip_start or long2ip(ip2long($ip_end)) != $ip_end) return NULL; 04 $ipl_start = (int)ip2long($ip_start); 05 $ipl_end = (int)ip2long($ip_end); 06 if($ipl_start > 0 && $ipl_end < 0) $delta = ($ipl_end + 4294967296) - $ipl_start; 07 else $delta = $ipl_end - $ipl_start; 08 $netmask = str_pad(decbin($delta), 32, "0", "STR_PAD_LEFT"); 09 if(ip2long($ip_start) == 0 && substr_count($netmask, "1") == 32) return "0.0.0.0/0"; 10 if($delta < 0 or ($delta > 0 && $delta % 2 == 0)) return NULL; 11 for($mask = 0; $mask < 32; $mask++) if($netmask[$mask] == 1) break; 12 if(substr_count($netmask, "0") != $mask) return NULL; 13 return "$ip_start/$mask"; 14 } 15 16 function GetNetMask($Ip) { 17 $WhoisUrl = "http://wq.apnic.net/apnic-bin/whois.pl?searchtext=" . $Ip . "&object_type=inetnum"; 18 19 if(!$WhoisUrlDataHandle = fopen($WhoisUrl, "r")) { 20 die("fopen(ERROR): $WhoisUrl"); 21 } 22 23 while ($line = fgets($WhoisUrlDataHandle)) { 24 if(preg_match("/(\d+)\.(\d+)\.(\d+)\.(\d+)[ \t]-[ \t](\d+)\.(\d+)\.(\d+)\.(\d+)/", $line, $match)) { 25 $ip0 = "$match[1].$match[2].$match[3].$match[4]"; 26 $ip1 = "$match[5].$match[6].$match[7].$match[8]"; 27 $mask = ip2cidr($ip0, $ip1); 28 break; 29 } 30 } 31 32 fclose($WhoisUrlDataHandle); 33 34 return $mask; 35 } 36 ?>