node142e4 Posted June 24, 2006 Share Posted June 24, 2006 Hello All,I am trying to determine if an ip-address with a notation like 192.168.1.312is in a network described with a notation like this 192.168.1.0/22I use an online tool IP calculator from [a href=\"http://jodies.de/ipcalc?host=192.168.1.0&mask1=22&mask2=\" target=\"_blank\"]http://jodies.de/ipcalc?host=192.168.1.0&mask1=22&mask2=[/a]this is the output:[code]Address: 192.168.1.0 11000000.10101000.000000 01.00000000Netmask: 255.255.252.0 = 22 11111111.11111111.111111 00.00000000Wildcard: 0.0.3.255 00000000.00000000.000000 11.11111111=>Network: 192.168.0.0/22 11000000.10101000.000000 00.00000000 (Class C)Broadcast: 192.168.3.255 11000000.10101000.000000 11.11111111HostMin: 192.168.0.1 11000000.10101000.000000 00.00000001HostMax: 192.168.3.254 11000000.10101000.000000 11.11111110Hosts/Net: 1022 (Private Internet)[/code]This shows that my example ip address is indeed in the network.To do this dynamically, all I can think of now is to put all 1022 ipaddresses in my db, and do a select where ... query.There must be a better way.Thanks very much in advance for any help or suggestions,node142e4 Quote Link to comment https://forums.phpfreaks.com/topic/12809-is-ipaddress-in-network/ Share on other sites More sharing options...
laie_techie Posted June 25, 2006 Share Posted June 25, 2006 First step: translate 192.168.1.0/22 into something you can use as a mask. 192.168.1.0/22 means that the first 22 bits of the IP in question must be identical to the first 22 bits in the base IP.BTW, each octet of the IP can be at most 255, so your sample IP of 192.168.1.312 was invalid.Untested code:[code=php:0]// Expects $base_ip and $ip to be in dotted formatfunction in_network( $base_id, $bit, $ip){ $base_ip = ip2long( $base_ip ); $test1 = $base_ip >> ( 32 - $bits ) $ip = ip2long($ip); $test2 = $ip >> (32 - $bits ); return $test1 == $test2;}if ( in_network('192.168.1.0', 22, '192.168.1.212') ){ echo "Same network!";}else{ echo "Different network!";}[/code] Quote Link to comment https://forums.phpfreaks.com/topic/12809-is-ipaddress-in-network/#findComment-49230 Share on other sites More sharing options...
node142e4 Posted June 25, 2006 Author Share Posted June 25, 2006 Thank you very much!besides two typos in the function signature, you're code works perfectly.I rarely have use for bitwise operators, but I do understand your solution and it is very nice and fast.cheers,node142e4 Quote Link to comment https://forums.phpfreaks.com/topic/12809-is-ipaddress-in-network/#findComment-49458 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.