[php]check if ip in ip range with subnet mask

有關網頁及相關語法的討論
回覆文章
頭像
tim
文章: 1379
註冊時間: 2008年 11月 26日, 00:49

[php]check if ip in ip range with subnet mask

文章 tim »

可以先利用這個線上工具查找或了解 subnet mask 的計算:

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");

所以是回傳 true, 又, 若有一串需要檢查的 ip_range_list 可以使用如下程式碼:

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;
    }
}
多多留言, 整理文章, 把經驗累積下來.....
回覆文章