PHP Conference Nagoya 2025

Fonctions réseaux

Sommaire

add a note

User Contributed Notes 10 notes

up
36
claudiu at cnixs dot com
17 years ago
A simple and very fast function to check against CIDR.

Your previous examples are too complicated and involves a lot of functions call.

Here it is (only with arithmetic operators and call only to ip2long () and split() ):
<?php
function ipCIDRCheck ($IP, $CIDR) {
list (
$net, $mask) = split ("/", $CIDR);

$ip_net = ip2long ($net);
$ip_mask = ~((1 << (32 - $mask)) - 1);

$ip_ip = ip2long ($IP);

$ip_ip_net = $ip_ip & $ip_mask;

return (
$ip_ip_net == $ip_net);
}
?>
call example: <?php echo ipCheck ("192.168.1.23", "192.168.1.0/24"); ?>
up
11
Anton Avramov - lukav at lukav dot com
7 years ago
An improved version of claudiu at cnixs dot com not using split and working with the following:
ip: 192.168.101.123, CIRD: 192.168.101.144/24

<?php
function ipCIDRCheck ($IP, $CIDR) {
list (
$net, $mask) = explode ('/', $CIDR);

$ip_net = ip2long ($net);
$ip_mask = ~((1 << (32 - $mask)) - 1);

$ip_ip = ip2long ($IP);

return ((
$ip_ip & $ip_mask) == ($ip_net & $ip_mask));
}
?>
up
5
Anonymous
8 years ago
improved version of philippe-at-cyberabuse.org's answer:

<?php
function cidrconv($net) {
$start = strtok($net,"/");
$n = 3 - substr_count($net, ".");
if (
$n > 0)
{
for (
$i = $n;$i > 0; $i--)
$start .= ".0";
}
$bits1 = str_pad(decbin(ip2long($start)), 32, "0", STR_PAD_LEFT);
$net = (1 << (32 - substr(strstr($net, "/"), 1))) - 1;
$bits2 = str_pad(decbin($net), 32, "0", STR_PAD_LEFT);
$final = "";
for (
$i = 0; $i < 32; $i++)
{
if (
$bits1[$i] == $bits2[$i]) $final .= $bits1[$i];
if (
$bits1[$i] == 1 and $bits2[$i] == 0) $final .= $bits1[$i];
if (
$bits1[$i] == 0 and $bits2[$i] == 1) $final .= $bits2[$i];
}
return array(
$start, long2ip(bindec($final)));
}
?>
up
2
David GASTALDIN
17 years ago
Here a IP-Range to CIDRs function that I wrote for the purpose of filling my Postfix client.cidr with ripe-ncc data to block spamming from useless countries. Strcmp functions are meant to work around the silly PHP string comparison which inevitably tries compare strings as numbers when possible. I'll make no comment about that fact ... bit I have to bite my tong hard :

function PlageVersCIDRs($ip_min, $ip_max) {
$cidrs = array();
$ip_min_bin = sprintf('%032b', $ip_min);
$ip_max_bin = sprintf('%032b', $ip_max);
$ip_cour_bin = $ip_min_bin;
while (strcmp($ip_cour_bin, $ip_max_bin) <= 0) {
$lng_reseau = 32;
$ip_reseau_bin = $ip_cour_bin;
while (($ip_cour_bin[$lng_reseau - 1] == '0') && (strcmp(substr_replace($ip_reseau_bin, '1', $lng_reseau - 1, 1), $ip_max_bin) <= 0)) {
$ip_reseau_bin[$lng_reseau - 1] = '1';
$lng_reseau--;
}
$cidrs[] = long2ip(bindec($ip_cour_bin)).'/'.$lng_reseau;
$ip_cour_bin = sprintf('%032b', bindec($ip_reseau_bin) + 1);
}
return $cidrs;
}
up
2
philippe-at-cyberabuse.org
22 years ago
PHP miss CIDR functions.

This one will convert a CIDR like this:
0.0.0.0/16 -> 0.0.0.0 - 0.0.255.255
127.0/16 -> 127.0.0.0 - 127.0.255.255
etc...

function cidrconv($net) {
$start=strtok($net,"/");
$n=3-substr_count($net, ".");
if ($n>0) { for ($i=$n;$i>0;$i--) $start.=".0"; }
$bits1=str_pad(decbin(ip2long($start)),32,"0","STR_PAD_LEFT");
$net=pow(2,(32-substr(strstr($net,"/"),1)))-1;
$bits2=str_pad(decbin($net),32,"0","STR_PAD_LEFT");
for ($i=0;$i<32;$i++) {
if ($bits1[$i]==$bits2[$i]) $final.=$bits1[$i];
if ($bits1[$i]==1 and $bits2[$i]==0) $final.=$bits1[$i];
if ($bits1[$i]==0 and $bits2[$i]==1) $final.=$bits2[$i];
}
return $start." - ".long2ip(bindec($final));
}
up
-1
nexxer at rogers dot com
19 years ago
In Trevor Hemsley's translation of the perl range2cidr function, the

while ($end > $start)

condition should be

while ($end >= $start)

otherwise it won't work for /32s, ie if you feed range2cidr("1.2.3.4", "1.2.3.4").

-- nex
up
-2
-dR
9 years ago
This little function might come in handy

<?php
function cidr_range( $cidr, $chkip=null )
{
// Assign IP / mask
list($ip,$mask) = explode("/",$cidr);

// Sanitize IP
$ip1 = preg_replace( '_(\d+\.\d+\.\d+\.\d+).*$_', '$1', "$ip.0.0.0" );

// Calculate range
$ip2 = long2ip( ip2long( $ip1 ) - 1 + ( 1 << ( 32 - $mask) ) );

// are we cidr range cheking?
if ( $chkip != null && ! filter_var( $chkip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false )
{
return
ip2long( $ip1 ) <= ip2long( $chkip ) && ip2long( $ip2 ) >= ip2long( $chkip ) ? true : false;
} else {
return
"$ip1 - $ip2";
}
}

var_dump( cidr_range( "127.0/16", "127.0.0.1" ) ); // bool(true)
var_dump( cidr_range( "127.0/16", "192.168.0.1" ) ); // bool(false)
var_dump( cidr_range( "192.168.0.0/24" ) ); // string(27) "192.168.0.0 - 192.168.0.255"

?>
up
-2
Anonymous
21 years ago
Alternative cidr_conv function - a little easier to follow

function cidr_conv($cidr_address) {
$first = substr($cidr_address, 0, strpos($cidr_address, "/"));
$netmask = substr(strstr($cidr_address, "/"), 1);

$first_bin = str_pad(decbin(ip2long($first)), 32, "0", STR_PAD_LEFT);
$netmask_bin = str_pad(str_repeat("1", (integer)$netmask), 32, "0", STR_PAD_RIGHT);

for ($i = 0; $i < 32; $i++) {
if ($netmask_bin[$i] == "1")
$last_bin .= $first_bin[$i];
else
$last_bin .= "1";
}

$last = long2ip(bindec($last_bin));

return "$first - $last";
}
up
-4
samuele at norsam dot org
21 years ago
To find if an IP is in a net/mask (very fast):
<?php
function isIPIn($ip,$net,$mask) {
$lnet=ip2long($net);
$lip=ip2long($ip);
$binnet=str_pad( decbin($lnet),32,"0","STR_PAD_LEFT" );
$firstpart=substr($binnet,0,$mask);
$binip=str_pad( decbin($lip),32,"0","STR_PAD_LEFT" );
$firstip=substr($binip,0,$mask);
return(
strcmp($firstpart,$firstip)==0);
}
?>

This function can be compacted, avoiding some variable settings, but the function will not be too clear to read...
Example code, used to made a kind of location service network-based:

<?php
$n
= array ( "192.168.0.0/16" => "TUSCANY",
"192.168.1.0/24" => "- Florence",
"192.168.2.0/24" => "- Pisa",
"192.168.3.0/24" => "- Siena",
"192.168.64.0/21" => "- Tuscan Archipelago",
"192.168.64.0/23" => "--- Elba Island",
"192.168.66.0/24" => "--- Capraia Island",
"192.168.67.0/24" => "--- Giannutri Island");

// Normally you should use the following line
$myip = $HTTP_SERVER_VARS['REMOTE_ADDR'];
// This is first example: returns Tuscany/Pisa
$myip = "192.168.2.33";
// This is second example: returns Tuscany/T.Arch./Elba
$myip = "192.168.65.34";

echo
"Your position:<br />\n";
foreach (
$n as $k=>$v ) {
list(
$net,$mask)=split("/",$k);
if (
isIPIn($myip,$net,$mask)) {
echo
$n[$k]."<br />\n"; }
}
?>

and so on...
up
-5
dand at ddchosting.com
18 years ago
When I was working on a project I ran into this problem with redirecting. My solution is as follows:
header("Refresh: 5; url=../main/main.php?".session_id()."");

This allowed me to pass the session_id() which is used throughout site to make sure user has loged in.
I hope this helps!
To Top