Last active
November 14, 2016 09:05
-
-
Save guweigang/ad0295311da1265849f7226785f799be 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 | |
function ipMatch($network, $ip) | |
{ | |
$network=trim($network); | |
$orig_network = $network; | |
$ip = trim($ip); | |
if ($ip == $network) { | |
echo "used network ($network) for ($ip)\n"; | |
return TRUE; | |
} | |
$network = str_replace(' ', '', $network); | |
if (strpos($network, '*') !== FALSE) { | |
if (strpos($network, '/') !== FALSE) { | |
$asParts = explode('/', $network); | |
$network = @ $asParts[0]; | |
} | |
$nCount = substr_count($network, '*'); | |
$network = str_replace('*', '0', $network); | |
if ($nCount == 1) { | |
$network .= '/24'; | |
} else if ($nCount == 2) { | |
$network .= '/16'; | |
} else if ($nCount == 3) { | |
$network .= '/8'; | |
} else if ($nCount > 3) { | |
return TRUE; // if *.*.*.*, then all, so matched | |
} | |
} | |
echo "from original network($orig_network), used network ($network) for ($ip)\n"; | |
$d = strpos($network, '-'); | |
if ($d === FALSE) { | |
$ip_arr = explode('/', $network); | |
if (!preg_match("@\d*\.\d*\.\d*\.\d*@", $ip_arr[0], $matches)){ | |
$ip_arr[0].=".0"; // Alternate form 194.1.4/24 | |
} | |
$network_long = ip2long($ip_arr[0]); | |
$x = ip2long($ip_arr[1]); | |
$mask = long2ip($x) == $ip_arr[1] ? $x : (0xffffffff << (32 - $ip_arr[1])); | |
$ip_long = ip2long($ip); | |
return ($ip_long & $mask) == ($network_long & $mask); | |
} else { | |
$from = trim(ip2long(substr($network, 0, $d))); | |
$to = trim(ip2long(substr($network, $d+1))); | |
$ip = ip2long($ip); | |
return ($ip>=$from and $ip<=$to); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment