вівторок, 2 листопада 2010 р.

Control IP against subnet

For developing web interface for control network with near 100 computers was need validate IP address of server against subnet .
The base of this function I found in internet, so only add control if  IP iscorrect:
function checkIpAgainstNetwork($ip,$network,&$error){
    //first need found Classe and Subnet
    $errore="";
    $connect = connectDB_connection_link($connect);
    $query_net=" select class,subnet from network where nome='".$network."'";
    $res1 = mysqli_query($connect,$query_net);
    $row = mysqli_fetch_assoc($res1);
    $class=$row["class"];
    $subnet=$row["subnet"];
    disconnectDB($connect);
    //ok, now need found first and last host ip
    $dqs=array(0=>$class,1=>$subnet);
    $dq_host=$dqs[0];
    $bin_nmask=dqtobin($dqs[1]);
    $bin_wmask=binnmtowm($bin_nmask);

    if (ereg("0",rtrim($bin_nmask, "0"))) { 
        $bin_wmask=dqtobin($dqs[1]);
        $bin_nmask=binwmtonm($bin_wmask);

        if (ereg("0",rtrim($bin_nmask, "0"))){
            $errore .= "Invalid subnet.<br>";
        }
    }
    $cdr_nmask=bintocdr($bin_nmask);

    //Check for valid $dq_host
    if(! ereg('^0.',$dq_host)){
        foreach( explode(".",$dq_host) as $octet ){
            if($octet > 255){
                $errore .= "Invalid IP Address";
            }

        }
    }

    $bin_host=dqtobin($dq_host);

    $bin_bcast=(str_pad(substr($bin_host,0,$cdr_nmask),32,1));

    $bin_net=(str_pad(substr($bin_host,0,$cdr_nmask),32,0));
    $bin_first=(str_pad(substr($bin_net,0,31),32,1));
    $bin_last=(str_pad(substr($bin_bcast,0,31),32,0));

    $dec_last=bintodq($bin_last);
    $dec_first=bintodq($bin_first);
    //now need check each octet to be not less than first and not more than last
   
    $array_octet_ip=explode(".",$ip);
    $array_octet_first=explode(".",$dec_first);
    $array_octet_last=explode(".",$dec_last);

    if (($array_octet_ip[0]<$array_octet_first[0]) or ($array_octet_ip[0]>$array_octet_last[0])){
        $errore .= "IP is not valid. Range is   $dec_first a $dec_last";
    }
    else if (($array_octet_ip[1]<$array_octet_first[1]) or ($array_octet_ip[1]>$array_octet_last[1])){
        $errore .= "IP is not valid. Range is   $dec_first a $dec_last";
    }
    else if (($array_octet_ip[2]<$array_octet_first[2]) or ($array_octet_ip[2]>$array_octet_last[2])){
        $errore .= "IP is not valid. Range is   $dec_first a $dec_last";
    }
    else if (($array_octet_ip[3]<$array_octet_first[3]) or ($array_octet_ip[3]>$array_octet_last[3])){
        $errore .= "IP is not valid. Range is   $dec_first a $dec_last";
    }

    if ($errore<>""){
        return false;
    }else{
        return true;
    }
}

Немає коментарів:

Дописати коментар