Jump to content


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


Is ipaddress in network?

Recommended Posts

Hello All,

I am trying to determine if an ip-address with a notation like
is in a network described with a notation like this

I use an online tool IP calculator from
[a href=\"http://jodies.de/ipcalc?host=\" target=\"_blank\"]http://jodies.de/ipcalc?host=[/a]
this is the output:
Address:           11000000.10101000.000000 01.00000000
Netmask: = 22    11111111.11111111.111111 00.00000000
Wildcard:             00000000.00000000.000000 11.11111111
Network:        11000000.10101000.000000 00.00000000 (Class C)
Broadcast:         11000000.10101000.000000 11.11111111
HostMin:           11000000.10101000.000000 00.00000001
HostMax:         11000000.10101000.000000 11.11111110
Hosts/Net: 1022                  (Private Internet)

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,


Share this post

Link to post
Share on other sites
First step: translate into something you can use as a mask. 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 was invalid.

Untested code:
// Expects $base_ip and $ip to be in dotted format
function 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('', 22, '') )
echo "Same network!";
echo "Different network!";

Share this post

Link to post
Share on other sites
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.



Share this post

Link to post
Share on other sites


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.