note 92544 modified in function.ip2long by danbrown

From: Date: Wed, 29 Jul 2009 03:13:10 +0000
Subject: note 92544 modified in function.ip2long by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-158855@lists.php.net to get a copy of this message
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): <?php 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("192.168.2.1","192.168.2.0",24); //true ip_in_network("192.168.6.93","192.168.0.0",16); //true ip_in_network("1.6.6.6","128.168.2.0",1); //false ?> --was-- 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("192.168.2.1","192.168.2.0",24); //true ip_in_network("192.168.6.93","192.168.0.0",16); //true ip_in_network("1.6.6.6","128.168.2.0",1); //false http://php.net/manual/en/function.ip2long.php

« previous php.notes (#158855) next »