mbeals Posted June 6, 2008 Share Posted June 6, 2008 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. Quote Link to comment https://forums.phpfreaks.com/topic/108989-solved-decbin-oddity/ Share on other sites More sharing options...
effigy Posted June 6, 2008 Share Posted June 6, 2008 I'm assuming your PHP_INT_MAX is less than $ip. base_convert($ip, 10, 2) works for me. Quote Link to comment https://forums.phpfreaks.com/topic/108989-solved-decbin-oddity/#findComment-559136 Share on other sites More sharing options...
mbeals Posted June 6, 2008 Author Share Posted June 6, 2008 good catch. I knew that the sprintf function was casting it to an unsigned integer, but I wasn't thinking of it like an integer. Changed that to a float and it seems to be working. thanks Quote Link to comment https://forums.phpfreaks.com/topic/108989-solved-decbin-oddity/#findComment-559141 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.