1. 程式人生 > 實用技巧 >PHP判斷IP是否屬於某個網段

PHP判斷IP是否屬於某個網段

第一種:

IP通過ip2long轉換後可以進行比較。

<?php
/**
 * 判斷IP是否在某個網路內 
 * @param $ip
 * @param $network
 * @return bool
*/

function ip_in_network($ip, $network)
{
    $ip = (double) (sprintf("%u", ip2long($ip)));
    $s = explode('/', $network);
    $network_start = (double) (sprintf("%u", ip2long($s[0])));
    $network_len = pow(2, 32 - $s[1]);
    $network_end = $network_start + $network_len - 1;

    if ($ip >= $network_start && $ip <= $network_end)
    {
        return true;
    }
    return false;
}

  第二種:

//案例:判斷192.168.1.127是否在 (192.168.1.1--192.168.1.255)的範圍裡面
 
$ip_start = get_iplong('192.168.1.1'); //起始ip
$ip_end = get_iplong('192.168.1.255');//至ip
$ip = get_iplong('192.168.1.127');//判斷的ip
//可以這樣簡單判斷
if($ip>=$ip_start && $ip <=$ip_end){
    echo 'IP在此範圍內';
}else{
    echo 'IP不在此範圍';
}
/**
 * 將ip地址轉換成int型
 * @param $ip  ip地址
 * @return number 返回數值
 */
function get_iplong($ip){
    //bindec(decbin(ip2long('這裡填ip地址')));
    //ip2long();的意思是將IP地址轉換成整型 ,
    //之所以要decbin和bindec一下是為了防止IP數值過大int型儲存不了出現負數。
    return bindec(decbin(ip2long($ip)));
}

  

轉載自:https://blog.csdn.net/jalin107/article/details/51396886https://blog.csdn.net/u010111874/article/details/51744253