Created
April 8, 2015 03:36
-
-
Save kasuganosora/9f8c10931e68f3769e1b to your computer and use it in GitHub Desktop.
更具域名剩下IP规则
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$domainsStr = <<<DOMAIN | |
twitter.com | |
facebook.com | |
instagram.com | |
youtube.com | |
google.com | |
ytimg.com | |
DOMAIN; | |
// 解析域名 | |
$domains = explode("\n", $domainsStr); | |
foreach ($domains as $i => $v) { | |
$domain = trim($v); | |
if($domain == ""){ | |
continue; | |
} | |
$domains[$i] = $domain; | |
} | |
// 把这些的A记录都归责到一起然后排序 | |
$aIPS = array(); | |
foreach ($domains as $i => $v) { | |
$records = dns_get_record($v); | |
foreach($records as $record){ | |
// 只要A记录, CNAME暂时没处理 | |
if($record["type"] != "A"){ | |
continue; | |
} | |
$aIPS[] = $record["ip"]; | |
} | |
} | |
// 去重和排序 | |
$aIPS = array_unique($aIPS); | |
natsort($aIPS); | |
$trees = array(); | |
// 生成IP树 | |
foreach ($aIPS as $ip) { | |
$ipBlocks = explode(".", $ip); | |
// Ablock | |
if(!isset($trees[$ipBlocks[0]])){ | |
$trees[$ipBlocks[0]] = array(); | |
} | |
// BBlock | |
if(!isset($trees[$ipBlocks[0]][$ipBlocks[1]])){ | |
$trees[$ipBlocks[0]][$ipBlocks[1]] = array(); | |
} | |
// CBlock | |
if(!isset($trees[$ipBlocks[0]][$ipBlocks[1]][$ipBlocks[2]])){ | |
$trees[$ipBlocks[0]][$ipBlocks[1]][$ipBlocks[2]] = array(); | |
} | |
// DBlock | |
$trees[$ipBlocks[0]][$ipBlocks[1]][$ipBlocks[2]][] = $ip; | |
} | |
$rules = array(); | |
// 生成网段规则; | |
foreach($trees as $keyA => $blockA){ | |
$countB = count($blockA); // 有多少个B段 | |
foreach ($blockA as $keyB =>$blockB) { | |
$countC = count($blockB); // 有多少个C段 | |
// 有连续3个C段IP的话就可能是同一机房 | |
if($countC > 3){ | |
$rules[] = "{$keyA}.{$keyB}.0.0/16"; | |
break; | |
} | |
foreach ($blockB as $keyC => $blockC) { | |
$countIP = count($blockC); // 有多少个IP | |
// 如果大于 3个IP是同一个C段的话, 就把整个C段放进规则里 | |
if($countIP > 3){ | |
$rules[] = "{$keyA}.{$keyB}.{$keyC}.0/24"; | |
}else{ | |
$rules = array_merge($rules, $blockC); // 如果只是 2的话直接用IP方式 | |
} | |
} | |
} | |
} | |
var_dump($rules); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment