[精讚] [會員登入]
1349

[PHP] IPv6檢查IP是否在某個網段內 mtachcidr6

要檢查IPv6是否在某個IPv6的網段內?

分享此文連結 //n.sfs.tw/12806

分享連結 [PHP] IPv6檢查IP是否在某個網段內 mtachcidr6@新精讚
(文章歡迎轉載,務必尊重版權註明連結來源)
2019-10-24 09:56:46 最後編修
2018-10-12 01:50:25 By 張○○
 

自動目錄

由於 IPv4 可以轉成十進位用推移的運算,但是 IPv6 要轉成十進位的話,會超過有效位數的顯示,另外由於ipv6本身是用十六進位表示,沒必要換成10進位。所以要用更漂亮的作法。我把他寫成 class  = =!!:

函式

/**
*   ipv6 class by axer@ms1.boe.tcc.edu.tw
*/
class ipv6{
    /**
    *   ExpandIPv6Notation2Bin()-  Convert an ipv6 address to bin string
    *   @param string $ip6 - an ipv6 address
    *   @return return the binary string of an ipv6 address if parameter ip6 is an ipv6 address,
    *           else it return an empty string.
    */
    public function ExpandIPv6Notation2Bin($ip6) {
        if (strpos($ip6, '::') !== false)
            $ip6 = str_replace('::', str_repeat(':0', 8 - substr_count($ip6, ':')).':', $ip6);
        $ip6parts = explode(':', $ip6);
        $res="";
        foreach ($ip6parts as $part)
            $res .= str_pad(base_convert( $part, 16, 2), 16, 0, STR_PAD_LEFT);
        return $res;
    }

    /**
    *   MatchCIDR6 -- Check if an ipv6 address is in the CDIR6 subnet.
    *   @param string $cidr6 - an ipv6 subnet, ex 2001:288:5400/39 or 2001:288:5432:/64 or 2001:288:5478::/64..
    *   @param string $chkipv6 - an ipv6 address, ex ::1, 2001:288:5200::1, :: ,etc.
    *   @return return true if $chkipv6 is inside the $cidr6 subnet, or return false.
    */
    public function MatchCIDR6( $cidr6, $chkipv6)
    {
        list($ip6, $prefixlen) = explode('/', $cidr6);
        $cidrbin= substr( $this->ExpandIPv6Notation2Bin($ip6), 0, $prefixlen);
        $chkip6bin= substr( $this->ExpandIPv6Notation2Bin($chkipv6), 0, $prefixlen);
        if(! strcmp($cidrbin,$chkip6bin))return true;
        return false;
    }
}

用法

$cidr6 = "2001:288:5400/39";
$ip6= "2001:288:5300:000::72A:4BE7";
$o_ipv6 = new ipv6();
// 檢查是ip6 是否在網段內
if( $o_ipv6->MatchCIDR6($cidr6,$ip6))
    print "Inside";
else
    print "Outside";

 

備註:有參考別人的程式,不過來源佚失了

 

相關連結

[PERL] 檢查IP是否在某個網段內:matchcidr


原文 2009-11-26

END

你可能感興趣的文章

[phpmyadmin] 錯誤:您應升級到 MySQL 5.5.0 或更新版本 使用phpmyadmin4出現錯誤:您應升級到 MySQL 5.5.0 或更新版本的解決方式

[PHP] 判斷文字、數字、文字加數字的方法 幾個PHP數字和文字操作上的小眉角:判斷文字、數字、文字加數字的方法

[PHP] 讀取作業系統程式執行結果 PHP讀取作業系統程式執行結果

作業上傳程式 提供學生作業上傳的程式

[CodeIgniter 3] 取得controller和method的方法 CodeIgniter 3 取得controller和method的方法

[PHP] codeignitor4+ smarty4 這篇整合 php 的framework codeignitor4 + smarty4。

我有話要說

>>

限制:留言最高字數1000字。 限制:未登入訪客,每則留言間隔需超過10分鐘,每日最多5則留言。

訪客留言

[無留言]

隨機好文

[Freebsd] 定時測試 ADSL 是否斷線並重連 中華電信 ADSL 雖有固定 ip,可是他卻會不定時「斷線」, 使用以下的 方法可以定時測試是否斷線,以及重新撥接。

[JAVA] JWS, JWT, JWE, JOSE是什麼? [JAVA] JWS, JWT, JWE, JOSE是什麼?非常的複雜,儘量來搞清楚..

好用的3+2碼郵遞區號查詢系統推薦 網路上找到用地址輸入判斷3+2碼郵遞區號的辨識率不高,除了這個網站…

魔球中小女孩唱的歌 The show 魔球中小女孩唱的歌 The show

[PHP] 檢查IP是否在某個網段內 mtachcidr 要檢查IP是否在某個網段內,要寫幾行?10行?5行? 不用,只要2行。以下是我寫的 code /** * matchCI