http://www.subnet-calculator.com/subnet.php
再來了解如何利用 php 程式判斷某 ip 是否在指定的 ip range, 如 192.168.1.10 有沒有在 192.168.1.1/24 裡 (答案是有)
參考程式碼:
https://gist.github.com/tott/7684443
代碼: 選擇全部
function ip_in_range( $ip, $range ) {
if ( strpos( $range, '/' ) == false ) {
$range .= '/32';
}
// $range is in IP/CIDR format eg 127.0.0.1/24
list( $range, $netmask ) = explode( '/', $range, 2 );
$range_decimal = ip2long( $range );
$ip_decimal = ip2long( $ip );
$wildcard_decimal = pow( 2, ( 32 - $netmask ) ) - 1;
$netmask_decimal = ~ $wildcard_decimal;
return ( ( $ip_decimal & $netmask_decimal ) == ( $range_decimal & $netmask_decimal ) );
}
ip_in_range("192.168.1.10", "192.168.1.1/24");
http://sandbox.onlinephpfunctions.com/c ... 1c7ab2b22c
代碼: 選擇全部
$ip_allow_list = array("192.168.1.10/24", "192.168.2.10/28", "192.168.3.15");
$remote_ip = "192.168.1.10";
foreach($ip_allow_list as $ip_allow){
if(ip_in_range($remote_ip, $ip_allow)){
echo $ip_allow;
break;
}
}