Tuesday, August 11, 2009

Check ip in network

I wanted to build on what kaputt and spinyn contributed in a way that I think is a little more intuitive (e.g., let sprintf do all the binary conversion and padding, and let substr_compare do the trimming and comparing):

function ip_in_network($ip, $net_addr, $net_mask){
    if($net_mask <= 0){ return false; }
        $ip_binary_string = sprintf("%032b",ip2long($ip));
        $net_binary_string = sprintf("%032b",ip2long($net_addr));
        return (substr_compare($ip_binary_string,$net_binary_string,0,$net_mask) === 0);

ip_in_network("","",24); //true
ip_in_network("","",16); //true
ip_in_network("","",1); //false

Source: jwadhams1 at yahoo dot com

No comments:

Post a Comment