Jump to content

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.