Jump to content

[SOLVED] decbin() oddity


mbeals

Recommended Posts

I have function that given a network address in slash notation will return an array of host ip's. It works for 90% of the IP's I hand to it, but for one particular one, it breaks and I can't figure out why. 

 

Here is the code:

 

function listIPs($ip,$mask){

	echo $ip.'<br>';

$ip = sprintf("%u",ip2long($ip));  //convert ip string to unsigned decimal 

	echo $ip.'<br>';

$freebits = 32 - $mask;         //calculate host bits from mask
$decfree =  pow(2,$freebits);  //calculate the number of hosts
$ips = array();

        ##### Create the subnet mask from the number of host bits #####
for($i=0;$i<32;$i++){
if($i<$freebits) continue;
$submask += pow(2,$i);
}

         echo "$ip<br>";

        #####Find the Subnet ID #########
$subnet = ($ip & $submask);

echo decbin($ip);

        #### Generate a list of hosts, ignoring the first (subnet ID) and last (broadcast) ip of the range###
for($i=1;$i<$decfree-1;$i++){

	$ips[] = long2ip($subnet + $i);

}

return $ips;

}

 

The echos are there for debugging.  When I run this code on the ip 199.227.155.164 / 30 I get the following output:

 

199.227.155.164
3353582500
3353582500
1111111111111111111111111111111

 

So the ip in string for (line 1) enters the function fine, it is converted to a long fine (line 2), it is still fine before entering the bitwise calc (line 3), but for some reason php's bitwise operations don't work on it (evident by decbin returning all 1's...line 4).  If you put 3353582500 into google's binary converter, it converts it to 11000111111000111001101110100100, which is the binary number that my subnet calculator is reporting the IP to be.  So there is something funky with the bitwise operation.

 

Any ideas on what is happening?  Like I said, it works fine for other addresses...this is the only one breaking it.

Link to comment
https://forums.phpfreaks.com/topic/108989-solved-decbin-oddity/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.